【问题标题】:How to reset fetch-mock for each test?如何为每个测试重置 fetch-mock?
【发布时间】:2018-03-01 15:48:10
【问题描述】:

我有几个使用 Jest 和 fetch-mock 的 React 测试,每个都做一些 get 操作,所以我最初做的是:

beforeAll(){
    fetchMock.get(`*`, JSON.stringify(CORRECTRESPONSE));
}

但是,在某些测试中,我需要返回错误的数据作为答案,例如:

test('Wrong get answer', ()=> {
   fetchMock.get('*', JSON.stringify(WRONGRESPONSE), {overwriteRoutes: true});
}));

所以,由于我需要重置以下测试的响应(因此返回 CORRECTRESPONSE,我想出了这个解决方案:

beforeEach(){
    fetchMock.get(`*`, JSON.stringify(CORRECTRESPONSE));
}

afterEach(fetchMock.restore);

还有更好的办法吗?

【问题讨论】:

    标签: reactjs unit-testing jestjs fetch fetch-mock


    【解决方案1】:

    我不明白为什么之前的答案 (https://stackoverflow.com/a/49778196/689944) 被设置为正确。 afterEach(fetchMock.restore) 测试后清理是一个非常好的方法。

    这也是 fetch-mock 文档中描述的内容:http://www.wheresrhys.co.uk/fetch-mock/#api-lifecyclerestore_reset

    【讨论】:

      【解决方案2】:

      根据文档应该这样做

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-01-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-29
        • 2021-12-22
        • 1970-01-01
        • 2017-09-15
        相关资源
        最近更新 更多