zl程序教程

您现在的位置是:首页 >  前端

当前栏目

[Unit Testing] Mock an HTTP request using Nock while unit testing

HTTP Using an request while Testing unit mock
2023-09-14 08:59:17 时间

When testing functions that make HTTP requests, it's not preferable for those requests to actually run. Using the nock JavaScript library, we can mock out HTTP requests so that they don't actually happen, control the responses from those requests, and assert when requests are made.

 

const assert = require('assert');
const nock = require('nock');
require('isomorphic-fetch');

function getData() {
    return fetch('https://jsonplaceholder.typicode.com/users')
        .then(response => response.json());
}

describe('getData', () => {
    it('should fetch data', () => {
        const request = nock('https://jsonplaceholder.typicode.com')
            .get('/users')
            .reply(200, [{username: 'joe'}]);

        getData()
            .then(response => {
                assert.deepEqual(response, [{username: 'joe'}]);
                assert.ok(request.isDone());
            });
    });
})