【问题标题】:How to pass mocked data for a GET call, in jest spyOn method如何以开玩笑的 spyOn 方法为 GET 调用传递模拟数据
【发布时间】:2019-08-28 10:34:11
【问题描述】:

如何使用 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

【问题讨论】:

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


【解决方案1】:

如果您的目标是模拟 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))
  })
});

【讨论】:

  • 感谢您的更新,但就我而言,我不想模拟整个 Axios [jest.mock('Axios')] 模块,我想监视类似于我的每个方法处理 POST 请求(spyOn(requests, 'request3') 见上文)。
猜你喜欢
  • 1970-01-01
  • 2018-05-05
  • 2021-06-26
  • 2019-07-09
  • 1970-01-01
  • 1970-01-01
  • 2019-03-23
  • 2020-03-15
相关资源
最近更新 更多