开玩笑地嘲笑axios不是在嘲笑

时间:2019-07-18 04:36:43

标签: jestjs axios

我正在尝试模拟具有以下代码(提取)的axios

const result await axios.patch(url, {customerId: '12345'});

为此,我正在做以下测试

import axios from "axios";
jest.mock("axios");
const mockedAxios = axios as jest.Mocked<typeof axios>;
mockedAxios.patch.mockImplementation(() => Promise.resolve({ status: 202 }));

但是,当我运行代码时,它不会运行我的模拟,而只会运行普通的axios库。

1 个答案:

答案 0 :(得分:0)

这是解决方案,您可以使用jest.fn()模拟axios模块的patch方法。

import axios from 'axios';

async function getCustomer() {
  const url = 'https://github.com/mrdulin';
  const result = await axios.patch(url, { customerId: '12345' });
  return result;
}

export { getCustomer };

单元测试:

import axios from 'axios';
import { getCustomer } from './';

describe('getCustomer', () => {
  it('t1', async () => {
    const url = 'https://github.com/mrdulin';
    axios.patch = jest.fn().mockResolvedValueOnce({ status: 202 });
    const actualValue = await getCustomer();
    expect(actualValue).toEqual({ status: 202 });
    expect(axios.patch).toBeCalledWith(url, { customerId: '12345' });
  });
});

单元测试结果:

 PASS  src/stackoverflow/57087200/index.spec.ts
  getCustomer
    ✓ t1 (8ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        2.608s