gpt4 book ai didi

javascript - 如何在 Jest 中测试 axios?

转载 作者:行者123 更新时间:2023-12-03 12:55:02 25 4
gpt4 key购买 nike

我在 React 中有这个 Action :

export function fetchPosts() {
const request = axios.get(`${WORDPRESS_URL}`);
return {
type: FETCH_POSTS,
payload: request
}
}

如何测试 Axios在这种情况下?

Jest 在他们的网站上有一个使用模拟函数的异步代码用例,但我可以使用 Axios 来做到这一点吗?

引用: An Async Example

到目前为止,我已经这样做了,以测试它是否返回正确的类型:

it('should dispatch actions with the correct type', () => {
store.dispatch(fetchPosts());
let action = store.getActions();
expect(action[0].type).toBe(FETCH_POSTS);
});

如何传入模拟数据并测试它返回的结果?

最佳答案

不使用任何其他库:

import * as axios from "axios";

// Mock out all top level functions, such as get, put, delete and post:
jest.mock("axios");

// ...

test("good response", () => {
axios.get.mockImplementation(() => Promise.resolve({ data: {...} }));
// ...
});

test("bad response", () => {
axios.get.mockImplementation(() => Promise.reject({ ... }));
// ...
});

可以指定响应代码:

axios.get.mockImplementation(() => Promise.resolve({ status: 200, data: {...} }));

可以根据参数更改模拟:

axios.get.mockImplementation((url) => {
if (url === 'www.example.com') {
return Promise.resolve({ data: {...} });
} else {
//...
}
});

Jest v23 引入了一些用于模拟 Promise 的语法糖:

axios.get.mockImplementation(() => Promise.resolve({ data: {...} }));

可以简化为

axios.get.mockResolvedValue({ data: {...} });

还有一个与被拒绝的 Promise 等效的方法:mockRejectedValue

进一步阅读:

关于javascript - 如何在 Jest 中测试 axios?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45016033/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com