Jest.js 用笑话嘲笑 axios 不是嘲笑

ars1skjm  于 2023-06-27  发布在  Jest
关注(0)|答案(1)|浏览(150)

我试图模仿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库。

mkshixfv

mkshixfv1#

选项1.使用jest.fn()创建一个mock函数并替换axios.patch()方法。
选项2.使用jest.spyOn(axios, 'patch').mockResolvedValueOnce({})
选项3. jest.mock('axios')也应该可以工作,jest会在需要时用自动模拟的版本模拟模块。

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

例如,使用选项1。

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

相关问题