Jest тестирование для топора ios запрос в node js - PullRequest
0 голосов
/ 24 марта 2020

Я новичок, чтобы реагировать 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 голосов
/ 25 марта 2020

Вот решение для модульного тестирования:

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
...