我有一个非常基本的组件,它使用axios.all对jokes api进行3次调用,然后将值存储在状态中。然后我将这些值映射到页面上。非常基本的东西。
我正在尝试编写一个模拟axios.all的测试,我可以将一些硬编码的响应传递给它。我想要证明数据绑定在调用解决后正确发生。
我很难做到这一点,我想知道是否有人有任何见解。
提前感谢大家的帮助!
发布于 2020-04-11 01:00:45
测试的问题在于您没有模拟axios方法。在导入库时简单地将其称为axiosMock不是它的工作方式。
你必须实际模拟你使用的方法:
describe("<TestScreen />", () => {
afterEach(() => {
cleanup();
jest.clearAllMocks();
});
beforeEach(() => {
// Mock all the calls to axios.get, each one returning a response.
axios.get = jest
.fn()
.mockResolvedValueOnce(RESPONSES[0])
.mockResolvedValueOnce(RESPONSES[1])
.mockResolvedValueOnce(RESPONSES[2]);
// Spy on spread method so that we can wait for it to be called.
jest.spyOn(axios, "spread");
});
test("placeholder", async () => {
const { queryAllByTestId } = render(<App />);
await waitFor(() => expect(axios.spread).toHaveBeenCalledTimes(1));
const setups = queryAllByTestId("setup");
const punchlines = queryAllByTestId("punchline");
expect(setups.length).toBe(3);
expect(punchlines.length).toBe(3);
});
});https://stackoverflow.com/questions/61125158
复制相似问题