Mocking class module in Jest

时间:2018-01-23 19:36:54

标签: javascript unit-testing mocking jestjs

Hey having problems mocking http requests in jest: That's my folder structure and files:

.
├── config
│   ├── __mocks__
│   │   └── api.js
│   └── api.js
├── handlers
│   ├── __tests__
│   │   └── getUser.js
│   └── getUser.js

config/__mocks__/api.js

const api = {
  get: (endpoint, config) =>
    new Promise(resolve => {
      resolve({ data: { type: 'test' } });
    }),
};
export default api;

config/api.js

import axios from 'axios';
import { SERVER } from './const';

const api = axios.create({
  baseURL: SERVER.PROD,
  timeout: 10000,
  headers: {
    Accept: 'application/json',
  },
});

export default api;

handlers/getUser.js

import api from '../config/api';
import { ENDPOINT } from '../config/endpoints';
import {serverResponseExtractor, errorHandler}  from '../util';

const getUsers = params => {
  const result = api.get(ENDPOINT).then(
      serverResponseExtractor,
    ),
    errorHandler,
  );

  return result;
};

export default getUsers;

handlers/__tests__/getUser-test.js

import getVods from '../getUser';

jest.mock('api');

test('getUsers> Returns valid User object', async () => {
  const currentOutput = await getUser(params);

  expect(currentOutput).toMatchSnapshot();
});

I'm basically trying to replace api on getUser with mocked version. I'm struggling with it for a long time and I can't make the getUser to use mocked api instead. The currentOutput always return actual api call instead of mocked response.

Is there something I'm missing or doing wrong?

2 个答案:

答案 0 :(得分:1)

你必须在调用jest.mock时使用相对路径:

index_name

答案 1 :(得分:0)

我使用jest.getMockFn()解决了它。标准模拟在模拟对象方面存在问题。

import api from '../../../src/provider/config/api';
import getUser from '../../../src/provider/handler/getUser';

import { getUserMocks } from './_handlersMocks';

api.get = jest.genMockFn();
api.get.mockImplementation(
  (url, config) =>
    new Promise((resolve, reject) => {
      resolve({ data: { items: ['getUserMocks.apiResponseMock'] } });
    }),
);
test(...)