0
0
PostmanHow-ToBeginner ยท 3 min read

How to Use pm.test in Postman for API Testing

Use pm.test in Postman to write tests by providing a test name and a function containing assertions. It helps verify API responses during your request execution by running the test and showing pass or fail results.
๐Ÿ“

Syntax

The pm.test function takes two arguments: a string for the test name and a function that contains the test code with assertions. Inside the function, you use pm.expect to check conditions.

  • pm.test(testName, testFunction): Defines a test with a name and logic.
  • testName: Describes what the test checks.
  • testFunction: Contains assertions to verify API response.
javascript
pm.test('Status code is 200', () => {
    pm.expect(pm.response.code).to.equal(200);
});
๐Ÿ’ป

Example

This example shows how to test that the API response status is 200 and the response body contains a specific key.

javascript
pm.test('Status code is 200', () => {
    pm.expect(pm.response.code).to.equal(200);
});

pm.test('Response has userId', () => {
    const jsonData = pm.response.json();
    pm.expect(jsonData).to.have.property('userId');
});
Output
PASS Status code is 200 PASS Response has userId
โš ๏ธ

Common Pitfalls

Common mistakes include forgetting to use arrow functions or regular functions inside pm.test, which causes syntax errors. Another mistake is not parsing the response JSON before accessing its properties, leading to runtime errors.

Also, using incorrect assertion methods or misspelling pm.expect will cause tests to fail unexpectedly.

javascript
/* Wrong: Missing function in pm.test */
pm.test('Status code is 200');

/* Correct: Provide a function with assertions */
pm.test('Status code is 200', () => {
    pm.expect(pm.response.code).to.equal(200);
});

/* Wrong: Accessing JSON without parsing */
pm.test('Check userId', () => {
    pm.expect(pm.response.userId).to.exist;
});

/* Correct: Parse JSON before checking */
pm.test('Check userId', () => {
    const data = pm.response.json();
    pm.expect(data).to.have.property('userId');
});
๐Ÿ“Š

Quick Reference

FeatureDescriptionExample
pm.testDefines a test with a name and functionpm.test('Test name', () => { /* assertions */ });
pm.expectAssertion library to check conditionspm.expect(pm.response.code).to.equal(200);
pm.response.json()Parses response body as JSONconst data = pm.response.json();
Test resultShows pass or fail in Postman test tabPASS or FAIL after running tests
โœ…

Key Takeaways

Use pm.test with a descriptive name and a function containing assertions to write tests.
Always parse JSON response with pm.response.json() before accessing its properties.
Use pm.expect for clear and readable assertions inside pm.test.
Check test results in Postman's Tests tab to verify API behavior.
Avoid syntax errors by always providing a function as the second argument to pm.test.