当前位置:网站首页>[postman] test script writing and assertion details

[postman] test script writing and assertion details

2022-07-06 06:09:00 lichong951

Test to confirm your API Work as expected , The integration between services runs reliably , And newly opened ​​ Hair does not destroy any existing functions . You can use JavaScript by Postman API Request to write test script . When your API When something goes wrong with the project , You can also use test code to help debug the process . for example , You can write a test , Verify by sending a request containing incomplete data or incorrect parameters API Error handling of .

You can add tests to individual requests in the collection 、 Collections and folders .Postman Contains code snippets that you add and then modify to suit your test logic .

To add a test to the request , Please open the request and click “ test ” Tab, enter your code . The test will be executed after the request to run . You will be able to “ test result ” See the output in the tab .
Here is a simple example
Assertions are defined as follows :

// Assert that the return status code is 200
pm.test(" Assert that the return status code is 200", function () {
    
    pm.response.to.have.status(200);
});

The results are as follows
 Insert picture description here

Writing assertions

Test scripts can use dynamic variables , Perform a test assertion on the response data , And pass data between requests . In the requested tests tab , Manually enter your JavaScript Or use the snippet you will see on the right side of the code editor .

Execute the test after receiving the response . When you select the Send when ,Postman Will respond to data from API Run your test script after returning .

Validation response

To verify the data returned by the request , You can pm.response Use this object in the test . Use this function to define tests pm.test, Provide a name and function , This function returns a Boolean (true or false) value , Indicates whether the test passed or failed . Use in your assertions ChaiJS BDD grammar pm.expect To test the response details .

The .test The first argument to the function is a text string , It will appear in the test result output . Use it to identify your tests , And communicate the purpose of the test to anyone who views the results .

for example , The requested “ test ” Tab to test whether the response status code is 200:

// Assert that the return status code is 200
pm.test(" Assert that the return status code is 200", function () {
    
    pm.response.to.have.status(200);
});

Select send to run your request and open the test results in the response section . The tab title shows how many tests passed and how many runs in total . You can also view Passed、Skipped and Failed Number of test results .

If the request returns 200 Status code , Pass the test . To see what happens to different status codes , Please change the expected state code in the test script and run the request again

Use pm.expect Format the test result message

Use this pm.expect Syntax can provide different formats for your test result messages . Try alternatives to achieve what you think is the most useful output .
Your code can test the request environment , As shown in the following example :

pm.test("environment to be production", function () {
    
    pm.expect(pm.environment.get("env")).to.equal("production");
});

You can use different syntax variants to write tests in a way that you think is readable and suitable for your application and test logic .

pm.test("response should be okay to process", function () {
    
    pm.response.to.not.be.error;
    pm.response.to.have.jsonBody("");
    pm.response.to.not.have.jsonBody("error");
});

Your test can use the syntax you customize for the response data format to determine the validity of the request response .

pm.test("response must be valid and have a body", function () {
    
     pm.response.to.be.ok;
     pm.response.to.be.withBody;
     pm.response.to.be.json;
});

Your script can contain as many tests as you need , And when you choose Save Will be saved with the rest of your request details . If you share a collection 、 Publish documents or use in Postman Middle run button , Your test code will be included in anyone who views or imports your template .

Test collections and folders

You can add test scripts to the collection 、 A single request in a folder or collection . The test script associated with the collection will run after each request in the collection . The test script associated with the folder will run after each request in the folder . This enables you to reuse commonly executed tests after each request . The order of execution of each request is set test , Folder test , Then there is the request test .

Adding scripts to collections and folders enables you to test API Workflow in the project . This helps ensure that your request covers typical scenarios , Provide a reliable experience for application users .

More action icons You can update the set and folder scripts by selecting the view more actions icon next to the set or folder name and selecting Edit . Select the test tab to add or update your script . You can also add a collection script the first time you create a collection .

When running a collection , You will see the test results output by the collection runner .
 Insert picture description here

Assert test script

Use your request 、 Folders and collections “ test ” Tab to write tests , These tests will be conducted in Postman Received a request from you API Execute when responding to . Add many tests you need for each request . When you add a test to a folder or collection , They will be executed after each of these requests .

Use multiple assertions

Your test can contain multiple assertions as part of a single test . Use it to combine related assertions :

pm.test("The response has all properties", () => {
    
    //parse the response JSON and test three properties
    const responseJson = pm.response.json();
    pm.expect(responseJson.type).to.eql('vip');
    pm.expect(responseJson.name).to.be.a('string');
    pm.expect(responseJson.id).to.have.lengthOf(1);
});

If any contained assertions fail , Then the whole test will fail . All assertions must succeed to pass the test .

Parse the response body data

To perform an assertion on your response , You first need to parse the data into what your assertions can use JavaScript object .

To parse JSON data , Please use the following syntax

const responseJson = pm.response.json();

To parse XML, Please use the following command :

const responseJson = xml2Json(pm.response.text());

To parse CSV, Please use CSV Parsing utility :

const parse = require('csv-parse/lib/sync');
const responseJson = parse(pm.response.text());

To parse HTML, Please use cheerio

const $ = cheerio.load(pm.response.text());
//output the html for testing
console.log($.html());

Handle unresolved responses

If you cannot parse the response body into JavaScript, Because it is not formatted as JSON、XML、HTML、CSV Or any other parseable data format , You can still assert data .

Test whether the response body contains a string :

pm.test("Body contains string",() => {
    
  pm.expect(pm.response.text()).to.include("customer_id");
});

This won't tell you where you encounter strings , Because it tests the entire response body . Test whether the response matches the string ( Usually only valid for short responses ):

pm.test("Body is string", function () {
    
  pm.response.to.have.body("whole-body-text");
});

Yes HTTP Respond with assertion

Your test can examine all aspects of the request response , Including text 、 The status code 、 header 、cookie、 Response time, etc .

Test response body

Check the specific value in the response body :

pm.test("Person is Jane", () => {
    
  const responseJson = pm.response.json();
  pm.expect(responseJson.name).to.eql("Jane");
  pm.expect(responseJson.age).to.eql(23);
});

Test status code

Test response status code :

pm.test("Status code is 201", () => {
    
  pm.response.to.have.status(201);
});

If you want to test whether the status code is one of a group , Please include them all in an array and use oneOf:

pm.test("Successful POST request", () => {
    
  pm.expect(pm.response.code).to.be.oneOf([201,202]);
});

Check the status code text :

pm.test("Status code name has string", () => {
    
  pm.response.to.have.status("Created");
});

Test header

Check whether there is a response header :

pm.test("Content-Type header is present", () => {
    
  pm.response.to.have.header("Content-Type");
});

Test the response header with a specific value :

pm.test("Content-Type header is application/json", () => {
    
  pm.expect(pm.response.headers.get('Content-Type')).to.eql('application/json');
});

test cookie
Test whether there is... In the response cookie:

pm.test("Cookie JSESSIONID is present", () => {
    
  pm.expect(pm.cookies.has('JSESSIONID')).to.be.true;
});

Test specific cookie value :

pm.test("Cookie isLoggedIn has value 1", () => {
    
  pm.expect(pm.cookies.get('isLoggedIn')).to.eql('1');
});

Test response time

Test whether the response time is within the specified range :

pm.test("Response time is less than 200ms", () => {
    
  pm.expect(pm.response.responseTime).to.be.below(200);
});

Assertion examples

Assert the response value for the variable

Check whether the response attribute is related to the variable ( In this case, the environment variable ) Has the same value :

pm.test("Response property matches environment variable", function () {
    
  pm.expect(pm.response.json().name).to.eql(pm.environment.get("name"));
});

Assertion value type

Test the type of any part of the response :

/* response has this structure: { "name": "Jane", "age": 29, "hobbies": [ "skating", "painting" ], "email": null } */
const jsonData = pm.response.json();
pm.test("Test data type of the response", () => {
    
  pm.expect(jsonData).to.be.an("object");
  pm.expect(jsonData.name).to.be.a("string");
  pm.expect(jsonData.age).to.be.a("number");
  pm.expect(jsonData.hobbies).to.be.an("array");
  pm.expect(jsonData.website).to.be.undefined;
  pm.expect(jsonData.email).to.be.null;
});

Assert array properties

Check if the array is empty , And whether it contains specific items :

/* response has this structure: { "errors": [], "areas": [ "goods", "services" ], "settings": [ { "type": "notification", "detail": [ "email", "sms" ] }, { "type": "visual", "detail": [ "light", "large" ] } ] } */

const jsonData = pm.response.json();
pm.test("Test array properties", () => {
    
    //errors array is empty
  pm.expect(jsonData.errors).to.be.empty;
    //areas includes "goods"
  pm.expect(jsonData.areas).to.include("goods");
    //get the notification settings object
  const notificationSettings = jsonData.settings.find
      (m => m.type === "notification");
  pm.expect(notificationSettings)
    .to.be.an("object", "Could not find the setting");
    //detail array must include "sms"
  pm.expect(notificationSettings.detail).to.include("sms");
    //detail array must include all listed
  pm.expect(notificationSettings.detail)
    .to.have.members(["email", "sms"]);
});

Assert object properties

Assert that an object contains keys or attributes :

pm.expect({
    a: 1, b: 2}).to.have.all.keys('a', 'b');
pm.expect({
    a: 1, b: 2}).to.have.any.keys('a', 'b');
pm.expect({
    a: 1, b: 2}).to.not.have.any.keys('c', 'd');
pm.expect({
    a: 1}).to.have.property('a');
pm.expect({
    a: 1, b: 2}).to.be.an('object')
  .that.has.all.keys('a', 'b');

The goal can be object、set or . If there is no or Operation in case of , The expression defaults to . Because behavior varies with goals , It is recommended to check before use with .arraymap.keys.all.any.all.keystypetype.keys.a

Assert a value in a collection

Check the response value according to the list of valid options :

pm.test("Value is in valid list", () => {
    
  pm.expect(pm.response.json().type)
    .to.be.oneOf(["Subscriber", "Customer", "User"]);
});

The assertion contains an object

Check whether the object is part of the parent object :

/* response has the following structure: { "id": "d8893057-3e91-4cdd-a36f-a0af460b6373", "created": true, "errors": [] } */

pm.test("Object is contained", () => {
    
  const expectedObject = {
    
    "created": true,
    "errors": []
  };
  pm.expect(pm.response.json()).to.deep.include(expectedObject);
});

Using.deep Cause all in the chain .equal, .include, .members, .keys, and .property Assert equal depth of use ( Loose equality ) Not strictly ( ===) equal . although .eql It's also loose , but .deep.equal The comparison that results in equal depth can also be used for any other assertion in the chain , and .eql Can't .

Assert the current environment

Check Postman Activities in ( The current choice ) Environmental Science :

pm.test("Check the active environment", () => {
    
  pm.expect(pm.environment.name).to.eql("Production");
});

Eliminate common test errors

When you encounter errors or unexpected behaviors in the test script ,Postman The console can help you identify the source . By way of console.log()、 and debug Statement combined with your test assertion console.info(), You can check HTTP Content of request and response , And things like variables Postman Data item . from Postman Select Console to open it .console.warn()console.error()

Record the value of a variable or response attribute :

console.log(pm.collectionVariables.get("name"));
console.log(pm.response.json().name);

Record the type of variable or response property :

console.log(typeof pm.response.json().id);

Use the console log to mark code execution , Sometimes called “ Trace statement ”:

if (pm.response.json().id) {
    
  console.log("id was found!");
  // do something
} else {
    
  console.log("no id ...");
  //do something else
}

Assertion of equal depth error

You may come across AssertionError: expected to deeply equal ‘’. for example , This will appear in the following code :

pm.expect(1).to.eql("1");

This happens because the test compares numbers with string values . Only when the type and value are equal , The test will return true.

JSON Undefined error

You may encounter this ReferenceError: jsonData is not defined problem . When you try to reference something that has not been declared or is outside the scope of the test code JSON Object time , This usually happens .

pm.test("Test 1", () => {
    
  const jsonData = pm.response.json();
  pm.expect(jsonData.name).to.eql("John");
});

pm.test("Test 2", () => {
    
  pm.expect(jsonData.age).to.eql(29); // jsonData is not defined
});

Ensure that all test code has access to any code that sets the response data as a variable , For example, in this case const jsonData = pm.response.json();, Move before the first code pm.test Will make it available to both test functions .

Assert undefined errors

You may encounter this AssertionError: expected undefined to deeply equal… problem . When you reference a property that does not exist or is out of range , This usually happens .

pm.expect(jsonData.name).to.eql("John");

In the example above , If you see AssertionError: expected undefined to deeply equal ‘John’, This shows that it's time to name Attribute is not in jsonData Object definition .

The test did not fail

In some cases , You may want the test to fail , But that's not the case .

//test function not properly defined - missing second parameter
pm.test("Not failing", function () {
    
    pm.expect(true).to.eql(false);
});

Make sure your test code is syntactically correct and send your request again .

Verify the response structure

Use Tiny Validator V4 (tv4) perform JSON Schema Validation :

const schema = {
    
 "items": {
    
 "type": "boolean"
 }
};
const data1 = [true, false];
const data2 = [true, 123];

pm.test('Schema is valid', function() {
    
  pm.expect(tv4.validate(data1, schema)).to.be.true;
  pm.expect(tv4.validate(data2, schema)).to.be.true;
});

Use Ajv JSON Schema validator validation JSON Pattern :

const schema = {
    
  "properties": {
    
    "alpha": {
    
      "type": "boolean"
    }
  }
};
pm.test('Schema is valid', function() {
    
  pm.response.to.have.jsonSchema(schema);
});

Send asynchronous request

Send the request from your test code and record the response .

pm.sendRequest("https://postman-echo.com/get", function (err, response) {
    
    console.log(response.json());
});
原网站

版权声明
本文为[lichong951]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060558575258.html