在Node JS中对Axios请求进行Jest测试

时间:2020-03-24 01:15:46

标签: javascript node.js jestjs axios

我是新来反应js和node js的人。我有一个连接到后端服务以获取数据的代码。现在,我需要使用Jest js对其进行单元测试。下面是我需要测试的代码:

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);
 }

};

下面是测试文件:

jest.mock('axios');

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

如何测试其余代码?

1 个答案:

答案 0 :(得分:0)

这是单元测试解决方案:

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);
  });
});

具有覆盖率报告的单元测试结果:

 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
相关问题