Test your API · Lesson 5 of 20
Write your first tests
Turn "it looks right" into checks that run on every send: status, fields, speed and shape.

Looking at a response tells you it works today. A test checks it for you every time you send, and later in CI on every change. Tests are short JavaScript snippets in the request's Scripts tab, under Post-response (they run after the response arrives).
Your first test
Open the Create user request from lesson 1 (or any request), go to Scripts → Post-response and type:
swc.test('responds with 200', () => {
swc.response.to.have.status(200);
});Send the request. The response panel now has a Tests tab showing 1/1 passed. Change 200 to 201 and send again to see what a failure looks like: the test turns red and says what it expected and what it got.
Not sure what to write? The snippet list beside the editor inserts common checks with one click.
Check the data
Most tests read the JSON body and check fields:
const user = swc.response.json();
swc.test('returns the user it created', () => {
swc.expect(user.json.name).to.equal('Ada');
swc.expect(user.json.role).to.be.oneOf(['admin', 'user']);
});
swc.test('answers in under 500 ms', () => {
swc.expect(swc.response.responseTime).to.be.below(500);
});
swc.test('sends JSON', () => {
swc.response.to.have.header('Content-Type');
swc.expect(swc.response.headers.get('Content-Type')).to.include('application/json');
});swc.expect uses the familiar Chai style: to.equal, to.eql (deep equal), to.include, to.be.above, to.have.property, to.be.a('string') and so on.
Check the shape with a schema
Instead of checking fields one by one, describe the shape once:
const schema = {
type: 'object',
required: ['id', 'email'],
properties: { id: { type: 'integer' }, email: { type: 'string' } },
};
swc.test('matches the user schema', () => {
swc.response.to.have.jsonSchema(schema);
});If you keep an OpenAPI definition in APIs, Swastik Codes can write these schema tests for every request at once: open the definition, go to its Contract tests tab and add them to the linked collection.
Pass data between requests
Tests often need a value from an earlier response, such as the id of the order you just created:
swc.collectionVariables.set('orderId', swc.response.json().id);The next request can use {{orderId}} in its URL. Run the requests in order with the collection runner (next lesson) and the chain works on every run.
Save an example
When a response is exactly right, click Save as example in the response bar. Examples document what the endpoint returns, power mock servers, and let Swastik Codes warn you with a Docs drift badge when a later response no longer matches what you documented.
What you learned
- Tests live in Scripts → Post-response and use
swc.testwithswc.expect. - Check status, fields, speed and whole schemas; store values for later requests with
swc.collectionVariables.set.
Next: run a whole collection of tested requests in one go.