【问题标题】:jest unit test case for fetch call react native用于获取调用的开玩笑单元测试用例反应本机
【发布时间】:2019-11-20 13:45:00
【问题描述】:

// 我的 fetch 调用的单元测试用例。我试图模拟 fetch 调用。当时我正在检查状态是否更新。我该怎么做呢

it('button press fetch data from json placeholder', async () => {
    global.fetch = jest.fn(
      () =>
        new Promise(resolve =>
          resolve({
            ok: true,
            json: () => Promise.resolve([1]),
          }),
        ),
    );

    const button = wrapper.find('[testID="inputButton"]');
    button.props().onPress();
    wrapper.update();
    console.log(wrapper.instance());
    expect(wrapper.instance().state.responseData.length).toBe(1);
  });

// 错误

Expected: 1
Received: 0

  44 |     wrapper.update();
  45 |     console.log(wrapper.instance());
> 46 |     expect(wrapper.instance().state.responseData.length).toBe(1);
     |                                                          ^
  47 |   });
  48 | });

// 组件中的实际代码

buttonPress = () => {
fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(res => res.json())
  .then(response => {
    this.setState({
      responseData: response,
    });
  });
};

【问题讨论】:

    标签: reactjs react-native jestjs enzyme


    【解决方案1】:

    尝试像这样解决承诺:

    global.fetch = jest.fn(() => new Promise.resolve({ok: true, json: <resolved value>})
    

    您通常希望通过以下方式解决您的所有承诺:

    return expect(Promise).resolves/rejects.<assertion>
    

    或者等待结果。

    【讨论】:

    • buttonPress = () =&gt; { fetch('https://jsonplaceholder.typicode.com/todos/1') .then(res =&gt; res.json()) .then(response =&gt; { this.setState({ responseData: response, }); }); } 你能给我这个 buttonPress 方法的确切代码
    • 这个家伙向我解释得很好:youtube.com/watch?v=uo0psyTxgQM
    【解决方案2】:

    // 应用 setTimeout() 后,我可以期待更新的状态值

    it('button press fetch data from json placeholder', async done => {
    global.fetch = jest.fn(
      () =>
        new Promise(resolve =>
          resolve({
            ok: true,
            json: () => Promise.resolve([1, 2]),
          }),
        ),
    );
    
    const button = wrapper.find('[testID="inputButton"]');
    button.props().onPress();
    wrapper.update();
    setTimeout(() => {
      expect(wrapper.instance().state.responseData.length).toBe(2);
      done();
      });
    });
    

    【讨论】:

      猜你喜欢
      • 2015-06-28
      • 2021-08-27
      • 1970-01-01
      • 1970-01-01
      • 2018-12-15
      • 2020-08-16
      • 1970-01-01
      • 2020-06-15
      • 1970-01-01
      相关资源
      最近更新 更多