在Jest中模拟具有可进行Axios调用的功能的对象

时间:2019-09-14 01:11:22

标签: mocking jestjs

我正在尝试在Jest中模拟一个对象,该对象将向我返回对象的属性,该对象是对Axios的函数调用。我已经使用Jest模块的默认导入语法进行了这项工作,但是我无法使其与mockImplementation一起工作,因此我需要这样做,以便每次都可以对其进行更改。

export const Users = {
  getUser: async id => {
    const result = await axios
      .get(`${user + id}.json`)
      .then(({ data }) => data);

    return result;
  },
};

在Jest中,我正在执行以下操作,并且效果很好,但是我想在每个测试中都进行更改,我该怎么做?我可以使用mockImplementation吗?

import { usersApi } from '../apis/Users';

jest.mock('../apis/Users', () => ({
  users: {
    getUser: () =>
      Promise.resolve({
        id: 1,
        name: "Joe"
      }),
  },
}));

我尝试了以下方法:

usersApi.mockImplementation({
  usersApi: {
    getUser: () => Promise.resolve('I am a user'),
  },
});

但是我得到的是

  

_usersApi.usersApi.mockImplementation不是函数

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

这是解决方案,您可以使用jest.spyOn.mockResolvedValueOnce

import axios from 'axios';

const user = 'user';

export const Users = {
  getUser: async id => {
    const result = await axios.get(`${user + id}.json`).then(({ data }) => data);
    return result;
  }
};

您可以在每个测试用例中使用.mockResolvedValueOnce方法模拟一次值:

import { Users } from './';

describe('test suites', () => {
  let getUserSpyOn;
  beforeEach(() => {
    getUserSpyOn = jest.spyOn(Users, 'getUser');
  });
  afterEach(() => {
    getUserSpyOn.mockRestore();
  });
  it('t1', async () => {
    const userMocked = { id: 1, name: 'Joe' };
    getUserSpyOn.mockResolvedValueOnce(userMocked);
    const actualValue = await Users.getUser(1);
    expect(actualValue).toEqual(userMocked);
  });
  it('t2', async () => {
    const userMocked = { id: 1, name: 'mrdulin' };
    getUserSpyOn.mockResolvedValueOnce(userMocked);
    const actualValue = await Users.getUser(1);
    expect(actualValue).toEqual(userMocked);
  });
});

单元测试结果:

 PASS  src/stackoverflow/57931751/index.spec.ts
  test suites
    ✓ t1 (9ms)
    ✓ t2 (1ms)

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        2.741s, estimated 3s