【发布时间】:2019-04-12 23:51:51
【问题描述】:
这是我想测试的一个类:
//Request.js
import axios, {AxiosInstance} from 'axios';
import config from './config';
const axiosSingleton: AxiosInstance = axios.create({
baseURL: 'http://localhost:8080',
});
export default class Request {
public async get<$ResponseType = any>(url: string): Promise<void> {
const response = await axiosSingleton.get(url);
return response.data;
}
}
当我尝试通过创建测试文件进行测试时,我不确定如何模拟 axios。我尝试了很多方法,包括 - spyOn 和自动模拟。但它们似乎不起作用。这是测试文件的一个版本,我不明白为什么它不起作用
// Request.test.js
import axios from 'axios';
import Request from './Request';
interface ITestResponseDataType {
value: string
}
jest.mock('axios');
describe('Request Tests', () => {
it('should call axios get with the right relativeUrl', async () => {
const getMock = jest.fn();
axios.create.mockReturnValue({
get: getMock
});
getMock.mockResolvedValue({
value: 'value'
});
const data = await new Request().get<ITestResponseDataType>('/testUrl');
expect(getMock.mock.calls.length).toEqual(1);
expect(data).toEqual({
value: 'value'
});
});
});
我尝试运行测试时遇到的错误是 -
TypeScript diagnostics (customize using `[jest-config].globals.ts-jest.diagnostics` option):
src/common/api/Request.test.ts:15:18 - error TS2339: Property 'mockReturnValue' does not exist on type '(config?: AxiosRequestConfig | undefined) => AxiosInstance'.
15 axios.create.mockReturnValue({
这个错误是有道理的,因为在 axios 中为 axios.create 定义的类型不应该允许在 .create 上调用 .mockReturnValue。那我怎么告诉 typescript jest 已经进去修改了呢?
【问题讨论】:
-
我遇到了同样的错误并在这里偶然发现......结果是我的模拟函数我实际上并没有调用 jest.fn()
标签: typescript axios jestjs mocking