【发布时间】:2019-08-28 10:34:11
【问题描述】:
如何使用 jest spyOn 方法将模拟数据传递给 GET 调用。
我最近开始使用 jest,用于模拟 API 请求我正在使用 jest spyOn 方法,我已经成功模拟了 post 请求,但无法为 GET 方法做到这一点
//用户流量
- 用户点击一个按钮,进行两次异步调用,然后呈现一个表单,用户填写并点击提交。
//Request.js
export const requestOne = async (id) => {
const { data }= await axios.get(`fake${id}/request-one`);
console.log(data);
return data;
};
export const requestTwo = async (id) => {
const { data } = await axios.get(`fake/request-two`);
return data;
};
export const requestThree = async (data) => {
await axios.put(`fake/request-three`, data);
return data;
};
//test.jsx
import * as requests from './requests';
describe('Test', () => {
it('should make both get calls on click of button', () => {
// This test is failing
const spyOne =
jest.spyOn(requests, 'requestOne').mockImplementationOnce(() =>
Promise.resolve(mockedRequestOneDetails));
const spyTwo = jest.spyOn(requests, 'requestTwo');
jest.spyOn(requests, 'requestTwo').mockImplementationOnce(() =>
Promise.resolve(mockedRequestTwoDetails));
const { container } = render(<Dom />);
// Unable to call requestOne and request two mocked data
})
it('should make post data to server', () => {
// This test is success
const spy = jest.spyOn(requests, 'requestThree ');
const { container } = render(<Dom />);
// Fill form details and submit
await wait(() => expect(spy).toHaveBeenCalledTimes(1));
})
});
当前工作解决方案: 对于获取电话
axios.get.mockImplementationOnce(() => Promise.resolve(mockedDataOne)); axios.get.mockImplementationOnce(() => Promise.resolve(mockedDataTwo));
预期: 类似于 post spyOn 方法,我应该能够发送模拟数据,类似于
jest.spyOn(requests, 'requestOne'); 将模拟数据发送到 requestOne 和 requestTwo
【问题讨论】:
-
看看axios-mock-adapter,可能就是你需要的。
标签: reactjs unit-testing jestjs react-testing-library