async node js jest unit tests

Viewed 33

This is my nodejs code and I want to unit tests using jest and mocking the request function. I am new to nodeJS, attached the mock function and the unit tests as well.

Please can someone add the right jest unit test code for below function.

async function getSomeTask(res) {
  request.get({ url: someTaskUrl }, (response, body) => {
    if (response.statusCode === 200) {
      res.writeHead(200, { 'content-type': 'application/json' });
      res.write(body);
      res.end();
      return;
    }
    const errorMessage = 'Failed';
    res.status(400).json({ error: errorMessage });
  });
}
// mock function in __mocks__
function get({url}) {
  return this;
}
const handler = require("../../handler");
const request = require("../__mocks__/request");
jest.mock("request");

describe("testHandler", () => {
    it("test", async () => {
    const response1 = {
      statusCode: 200,
      body: { Test: "test" },
    };
    const url = "http://example.com";

    jest.fn().mockImplementation({ url }, (response, body) => {
      return Promise.resolve(response1);
    });
    const req = {
      body: { requestId: 1111 },
      capabilitiesCheckUrl: "http://capabilities-test",
    };
    const res = {};
    const resp = handler.getSomeTask(res);
    console.log(resp);
  });
});

If possible give me an explanation as well.

1 Answers

You don't need to mock the entire request module by using jest.mock('request') and creating mocks inside __mocks__ directory. You can use jest.spyOn(request, 'get') to only mock request.get method.

handler.js:

const request = require('request');

const someTaskUrl = 'http://localhost:3000/api'
async function getSomeTask(res) {
  request.get({ url: someTaskUrl }, (response, body) => {
    if (response.statusCode === 200) {
      res.writeHead(200, { 'content-type': 'application/json' });
      res.write(body);
      res.end();
      return;
    }
    const errorMessage = 'Failed';
    res.status(400).json({ error: errorMessage });
  });
}

module.exports = {
  getSomeTask,
};

handler.test.js:

const handler = require('./handler');
const request = require('request');

describe('73754637', () => {
  test('should get some task success', () => {
    jest.spyOn(request, 'get').mockImplementation((options, callback) => {
      const mResponse = { statusCode: 200 };
      const mBody = { Test: 'test' };
      callback(mResponse, mBody);
    });
    const mRes = {
      writeHead: jest.fn(),
      write: jest.fn(),
      end: jest.fn(),
    };
    handler.getSomeTask(mRes);
    expect(request.get).toBeCalledWith({ url: 'http://localhost:3000/api' }, expect.any(Function));
    expect(mRes.writeHead).toBeCalledWith(200, { 'content-type': 'application/json' });
    expect(mRes.write).toBeCalledWith({ Test: 'test' });
    expect(mRes.end).toBeCalledTimes(1);
  });
});

Test result:

 PASS  stackoverflow/73754637/handler.test.js (10.283 s)
  73754637
    ✓ should get some task success (5 ms)

------------|---------|----------|---------|---------|-------------------
File        | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
------------|---------|----------|---------|---------|-------------------
All files   |   81.82 |       50 |     100 |   81.82 |                   
 handler.js |   81.82 |       50 |     100 |   81.82 | 12-13             
------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        10.807 s, estimated 11 s
Related