在使用axios
时,遇到以下错误:
TS2339(TS)类型“AxiosStatic”上不存在属性“mockResolvedValueOnce”
尝试使用axios as jest.Mock
,但是出现以下错误:
TS2352(TS)将类型“AxiosStatic”转换为类型“Mock<any,any>”可能是一个错误,
因为两种类型都没有足够的重叠。如果这是有意的,请先将表达式转换为“unknown”。
类型“AxiosStatic”缺少类型“Mock<any,any>”的以下属性:getMockName、
mock、mockClear、mockReset以及其他12个。
通过指定axios as unknown as jest.Mock
来解决此问题。
AxiosRequest.test.tsx
import axios from 'axios';
import { MediaByIdentifier } from '../api/mediaController';
jest.mock('axios', () => jest.fn());
test('Test AxiosRequest',async () => {
const mRes = { status: 200, data: 'fake data' };
(axios as unknown as jest.Mock).mockResolvedValueOnce(mRes);
const mock = await MediaByIdentifier('Test');
expect(mock).toEqual(mRes);
expect(axios).toHaveBeenCalledTimes(1);
});
媒体控制器.ts:
import { sendRequest } from './request'
import { AxiosPromise } from 'axios'
import { MediaDto } from './../model/typegen/mediaDto';
const path = '/api/media/'
export const MediaByIdentifier = (identifier: string): AxiosPromise<MediaDto> => {
return sendRequest(path + 'MediaByIdentifier?identifier=' + identifier, 'get');
}
请求.ts:
import axios, { AxiosPromise, AxiosRequestConfig, Method } from 'axios';
const getConfig = (url: string, method: Method, params?: any, data?: any) => {
const config: AxiosRequestConfig = {
url: url,
method: method,
responseType: 'json',
params: params,
data: data,
headers: { 'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/json' },
}
return config;
}
export const sendRequest = (url: string, method: Method, params?: any, data?: any): AxiosPromise<any> => {
return axios(getConfig(url, method, params, data))
}
import * as _ from ''
一样导入整个库,因为间谍被应用于一个对象。 - windmaomao