mockAxios.create = jest.fn(() => mockAxios); mockAxios.get = jest.fn(() => Promise.resolve({ data: {} })); mockAxios.post = jest.fn(() => Promise.resolve({ data: {} })); mockAxios.put = jest.fn(() => Promise.resolve({ data: {} })); mockAxios.delete = jest.fn((...
1totalTests:2passed,2totalSnapshots:0totalTime:4.483s,estimated 5s
首先,安装所需的依赖: npm install axios axios-mock-adapter jest --save-dev 1. 然后,创建一个名为httpService.test.js的测试文件,编写以下代码: import axios from 'axios'; import MockAdapter from 'axios-mock-adapter'; import { post } from './httpService'; describe('httpService', () => { ...
import axios from "axios"; axios.defaults.baseURL = 'http://xxx.cn' //axios.defaults.headers...
// 通过`axios`mock提交表单的接口返回数据 test('form表单提交数据', async () => { // mock数据 将入参name, password 拼接成token字段返回 组件中将返回的token存储到localStorage中 axios.post.mockImplementationOnce((url, body) => { const { name, password } = body?.data ...
Jest中Mock网络请求 最近需要将一个比较老的库修改为TS并进行单元测试,修改为TS还能会一点,单元测试纯粹是现学现卖了,初学Jest框架,觉得在单元测试中比较麻烦的就是测试网络请求,所以记录一下Mock掉Axios发起网络请求的一些方式。初学两天的小白,如有问题还请指出。
上面的代码是jest.fn()提供的几个常用的API和断言语句,下面我们在src/fetch.js文件中写一些被测试代码,以更加接近业务的方式来理解Mock函数的实际应用。 被测试代码中依赖了axios这个常用的请求库和JSONPlaceholder这个上篇文章中提到免费的请求接口,请先在shell中执行npm install axios --save安装依赖,。
// ./test/UppercaseProxy.spec.jsimportmockAxiosfrom'jest-mock-axios';importUppercaseProxyfrom'../src/UppercaseProxy';afterEach(()=>{// cleaning up the mess left behind the previous testmockAxios.reset();});it('UppercaseProxy should get data from the server and convert it to UPPERCASE'...
Interestingly, reordering the test like this still fails but does pass the call assertion, so mockAxios.post is definitely still being called:it('should call the correct endpoint', async () => { const promise = callEndpoint('some-data') expect(mockAxios.post).toHaveBeenCalledWith('/...
1.2 fetchData来源(这里是浪费时间的源头,网上实例一般都是通过axios.post直接发起请求,通过axios-mock-adapter的示例代码可以成功mock请求,但是我们项目中是通过axios.create创建了新的实例,所以要理解<new MockAdapter>的参数,是axios的一个实例) function fetcherCreator(url, userInfo) { const fetcher = axios.creat...