1

I am new to react js and node js. I have a code which connects to a back-end service to fetch data. Now i need to write unit test to it using jest js. Below is the code i need to test:

const axios = require('axios');
const {host, token} = require('./config');

const getData = async (req, mainRes) => {
 try {
  let token = await token();
  let {data} = await axios({
   method: 'GET',
   url: `${host}/api/books`,
   headers: {
     Authorization: `${token}`
   }
 });
 mainRes.status(200).json(data);
 } catch (error) {
  errorHandler(error.message, mainRes);
 }

};

Below is the test file:

jest.mock('axios');

const axios = require('axios');
const {host, token} = require('./config');
const file = require('../file');

How to test the rest of the code?

1

1 Answer 1

2

Here is the unit test solution:

index.js:

const axios = require('axios');
const { host, token } = require('./config');
const { errorHandler } = require('./errorHandler');

export const getData = async (req, mainRes) => {
  try {
    let tk = await token();
    let { data } = await axios({
      method: 'GET',
      url: `${host}/api/books`,
      headers: {
        Authorization: `${tk}`,
      },
    });
    mainRes.status(200).json(data);
  } catch (error) {
    errorHandler(error.message, mainRes);
  }
};

errorHandler.js:

export const errorHandler = (message, mRes) => null;

config.js:

export async function token() {
  return '123';
}

export const host = 'localhost';

index.test.js:

import * as mod from '.';
const { token } = require('./config');
const axios = require('axios');
const { errorHandler } = require('./errorHandler');

jest.mock('./config', () => {
  const config = require.requireActual('./config');
  return { token: jest.fn(), host: config.host };
});

jest.mock('axios', () => jest.fn());
jest.mock('./errorHandler', () => {
  return { errorHandler: jest.fn() };
});

describe('60823714', () => {
  it('should get books', async () => {
    token.mockResolvedValueOnce('abc');
    axios.mockResolvedValueOnce({ data: { books: [] } });
    const mReq = {};
    const mRes = { status: jest.fn().mockReturnThis(), json: jest.fn() };
    await mod.getData(mReq, mRes);
    expect(token).toBeCalled();
    expect(axios).toBeCalledWith({
      method: 'GET',
      url: 'localhost/api/books',
      headers: { Authorization: `abc` },
    });
    expect(mRes.status).toBeCalledWith(200);
    expect(mRes.json).toBeCalledWith({ books: [] });
  });

  it('should handle error', async () => {
    token.mockResolvedValueOnce('abc');
    const mError = new Error('network');
    axios.mockRejectedValueOnce(mError);
    const mReq = {};
    const mRes = { status: jest.fn().mockReturnThis(), json: jest.fn() };
    await mod.getData(mReq, mRes);
    expect(token).toBeCalled();
    expect(axios).toBeCalledWith({
      method: 'GET',
      url: 'localhost/api/books',
      headers: { Authorization: `abc` },
    });
    expect(errorHandler).toBeCalledWith('network', mRes);
  });
});

unit test results with coverage report:

 PASS  stackoverflow/60823714/index.test.js
  60823714
    ✓ should get books (6ms)
    ✓ should handle error (2ms)

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------|---------|----------|---------|---------|-------------------
All files  |   93.75 |      100 |   66.67 |   90.91 |                   
 config.js |   66.67 |      100 |       0 |   66.67 | 2                 
 index.js  |     100 |      100 |     100 |     100 |                   
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        3.876s, estimated 7s
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.