![](/img/trans.png)
[英]Why does Axios get call return a 404 error with basic setup?
[英]Why does mocked axios get method return undefined?
我编写了一个相当简单的异步方法,该方法通过HTTP检索结果:
import axios from "axios";
const BASE_URI = "http://api.tvmaze.com";
export const getSearchShows = async (search: string) => {
const uri = `${BASE_URI}/search/shows?q=${encodeURIComponent(search)}`;
const response = await axios.get(uri);
return response.data;
};
我想对其进行单元测试。 因此,我编写了以下Jest测试,该测试旨在模拟axios并返回假结果,然后可以对其进行断言:
import axios from "axios";
import fakeSearchShowsResponse from "../data/search-shows--q=test.json";
import { getSearchShows } from "./TvShows.http";
jest.mock("axios");
describe("TvShows.http", () => {
describe("getSearchShows", () => {
it("retrieves shows over http and correctly deserializes them", async () => {
const mockAxiosGet = jest.spyOn(axios, "get");
mockAxiosGet.mockImplementation(async () => fakeSearchShowsResponse);
const shows = await getSearchShows("test");
console.log(mockAxiosGet.mock.calls);
expect(shows[0].id).toEqual(139);
});
});
});
我预计,由于调用jest.mock("axios")
,axios get方法将被模拟的Jest方法取代。
此外,我期望由于调用了mockAxiosGet.mockImplementation
并将其传递给函数,因此对axios get方法的调用实际上会调用我的模拟函数,从而使我可以用测试数据代替真实数据。
实际发生的是对axios get的调用undefined
返回,导致我的测试断言失败。
然而,奇怪的是,Jest间谍仍在注册该方法已被调用– console.log输出一个调用。
那么,当我明确提供一个返回值的模拟实现时,为什么这个模拟方法返回undefined
状态?
还是我会误解了应如何使用模拟实现?
因此,经过一些试验,看来jest.mock("axios")
调用正在干扰jest.spyOn(axios, "get");
呼叫。
删除jest.mock调用后,它现在从jest.spyOn调用返回我的模拟值。
我认为这可能是因为jest.mock调用被挂起,而jest.spyOn调用没有被挂起。 因此,受测模块是从吊装的模拟机上卸下的,而不是从未吊装的模拟机上卸下的。
jest.mock('axios')
会模拟整个模块,并用存根替换所有内容。 因此,它不一定与悬挂jest.mock()
的事实有关,而只是确保在导入之前jest.mock()
依赖项。 只是存根返回undefined
。
同时,您可以
import axios from 'axios';
jest.mock('axios');
console.log(axios); // mocked
describe('suite', () => {
it('test', () => {
axios.get.mockResolvedValue('{"test": "test"}');
// --------------------------^
// you class would get this when calling axios.get()
// you could also do some assertion with the mock function
expect(axios.get).toHaveBeenCalledTimes(1);
expect(axios.get).toHaveBeenCallWith('http://some-url');
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.