首页 > 解决方案 > 如何模拟在同一函数中进行的多个 fetch 调用

问题描述

我有一个函数,如下所示,它在同一个函数中执行 2 个 fetch 调用

getNames() {
    var qs = require("qs");
    fetch(<URL>,
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
        },
        body: qs.stringify({
          firstName: this.state.firstName,
          lastName: this.state.lastName
        })
      })
      .then(response => response.json()).then((data) => {
        console.log(data)
      });

    var url = new URL(<someURL>)

    fetch(<someURL>).then(response => response.json()).then((data) => {
     ...do something...
      }
     })
      .catch(error => {
        alert("no response");

        console.log(error);
      });
  }

我正在使用 Jest 和 Enzyme on React 对此进行测试。以上属于 GetName 组件。下面是我的测试用例:

describe('getName', () => {
    const wrapper = shallow(<GetName />).instance();

    beforeEach(() => {
        global.fetch.resetMocks();
    });

    it('positive flow', () => {
        global.fetch.mockResolvedValue(
            new Response(JSON.stringify({data: "mockData"}))
        );
        const state = {
            firstName: "don",
            lastName: "Lee"
        };
        wrapper.setState(state);
        const actualValue = wrapper.getNames();
        expect(actualValue).toBeUndefined();
    });
 });

一旦我这样做,我会收到一个错误TypeError: body used already for: undefined

我知道这里的 fetch 用于 POST 调用,但是我如何确保我可以在函数中模拟两个 fetch 调用?

我也试过fetch.mockResponseand fetch.mockResponsesand also fetch.mockResponseOnce。它们似乎都没有帮助我不止一次地模拟它们,并且提到的所有功能都出现了这个错误。

有没有其他方法可以模拟两个 fetch 调用?

标签: javascriptreactjsjestjsenzyme

解决方案


推荐阅读