All Posts All Posts

API Testing with Supertest

April 23, 2017·
Software Engineering
·2 min read
Tecker Yu
Tecker Yu
AI Native Cloud Engineer × Part-time Investor

In Node.js development, after completing API interfaces, testing is often required. Commonly used testing modules are generally mocha and chai. We should also have corresponding request modules to help us better accomplish assertion tasks. Today’s main topic is supertest.

Those who have used superagent should know that supertest has equally concise and elegant usage. This article is based on Express. Without further ado, let’s dive into practical code examples.

GET Request

const assert = require('chai').assert;
const request = require('supertest');
const should = require('should');
const app = require('../../app');
const _ = require('lodash');
// Setting supertest as request is out of habit

// Assertion
describe("get /", function() {
    // it describes the API functionality and expected return content
    it("should respond with ....", function() {
        // Use supertest to perform GET request and verify its returned status code
        return request(app).get('/')
            .set('Accept', 'application/json')  // set request header
            .expect(200)    // expected status code
            .then(function(res) {
                assert.notEqual(_.findIndex(res.body, {
                    // Use assert assertion library for assertions. If lodash can't find the key-value pair in the outermost layer of JSON (for inner content you can continue accessing based on body)
                    // Using equal or to.include.keys('key') is also acceptable
                    'key' : 'value'
                }), -1);
            })
    })
}

POST Request

// No need to repeat the above, we focus on supertest
return request(app).post('/search')
        .send({ key: 'value' })     // x-www-form-urlencoded
        .field('name', 'Jack')      // form-data
        .attach('avatar', 'test/fixtures/homeboy.jpg')  // post file upload

PUT or DELETE Requests

Similarly

request(app).del('/path')
request(app).put('/path')

Views