每次测试后,jest-fetch都不会重置

时间:2018-06-18 13:09:23

标签: fetch jestjs jest-fetch-mock

因为标题暗示fetch.mockResets()没有重置fetch,导致我的测试中断,我使用jest-fetch-mock包来模拟获取api。

根据jest-fetch-mock文档,调用fetch.resetMocks()应该重置fetch对象,但我似乎无法使它工作

这是我的完整test.spec.js:

import Statistic from './Statistics';
import Worker from '../statistics-worker/worker';
jest.mock("../statistics-worker/worker");
const workerInitProps = {
  interactionId: '123',
  interactionSubmissionUrl: 'submission',
  fetchUrl: 'fetch'
};
const statService = Statistic.getNewInstance(new Worker(workerInitProps));
describe('Statistic serivce ', () => {
  beforeEach(() => {
    fetch.resetMocks();
  });
  it('Should init worker', () => {
    expect(statService).toBeInstanceOf(Statistic);
  });
  it('should fetch statistics', () => {
    fetch.mockResponseOnce(
      JSON.stringify({
        payload: {
          statistics: {
            1: 10,
            2: 11
          },
          count: 10,
          finalResults: []
        }
      })
    );
    statService
      .fetchStatistics()
      .then(res => {
        expect(res).toEqual({
          statistics: {
            1: {
              options: 10,
              totalVotes: 0
            },
            2: {
              options: 11,
              totalVotes: 0
            }
          },
          count: 10,
          finalResults: []
        });
      })
      .catch(err => {
        expect(err).toBeFalsy();
      });
  });

  it('should deadlock fetch statistics', () => {
    fetch.mockRejectOnce(new Error('fake error message'));

    statService
      .fetchStatistics()
      .then(res => {
        console.log(res);
        expect(res).toEqual({
          count: 0,
          statistics: {},
          dead: true
        });
      })
      .catch(err => {
        expect(err).toBeFalsy();
      });
  });
});

我得到的结果是:

Expected value to equal:
  {"count": 0, "dead": true, "statistics": {}}
Received:
  {"count": 10, "finalResults": [], "statistics": {"1": {"options": 10, "totalVotes": 0}, "2": {"options": 11, "totalVotes": 0}}}

0 个答案:

没有答案