如何通过jest spyOn方法为GET调用传递模拟数据

时间:2019-08-28 10:34:11

标签: reactjs unit-testing jestjs react-testing-library

如何使用jest spyOn方法将模拟数据传递给GET调用。

我最近开始使用jest,用于模拟API请求,我正在使用jest spyOn方法,我已成功模拟了post请求,但无法针对GET方法进行

//用户流

  1. 用户单击一个按钮,该按钮将进行两个异步调用,然后呈现一个表单,用户将填写并单击提交。
//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

1 个答案:

答案 0 :(得分:0)

如果您的目标是模拟GET请求中的数据,则可以使用jest.mock代替Jest docs所示:

import Component from "./Component"
import axios from 'axios';

jest.mock('axios');

test('should fetch users', async () => {
  const users = ["Bob", "John", "Jane"]
  const response = {data: users};
  axios.get.mockResolvedValue(response);

  const { getByText } = render(<Component/>)

  await wait(() => {
    users.forEach(user => getByText(user))
  })
});