我正在尝试测试此简单的api模块:

import fetch from 'isomorphic-fetch';

export const getJson = (endpoint: string) => {
  const options = { credentials: 'include', method: 'GET' };

  return fetch(endpoint, options)
    .then(response => response.json()
      .then(json => {
        if (response.ok) return json;
        return Promise.reject(json.errors);
      })
    )
    .catch(error => {
      if (error.constructor === Array) return error;
      return [error.message];
    });
};


通过此测试,我在其中模拟访存:

import { getJson } from '../api';

const mockResponse = (status, statusText, response) => {
  return new window.Response(response, {
    status: status,
    statusText: statusText,
    headers: {
      'Content-type': 'application/json'
    }
  });
};

describe('api middleware', () => {
  describe('getJson', () => {
    it('should return the response on success', () => {
      const expected = { data: ['data'], meta: {} };
      const body = JSON.stringify(expected);

      window.fetch = jest.fn().mockImplementation(() =>
        Promise.resolve(mockResponse(200, null, body)));

      return getJson('http://endpoint').then(actual => expect(actual).toEqual(expected));
    });
  });
});


但是测试失败并显示:

Expected value to equal:
  {"data": ["data"], "meta": {}}
Received:
  ["Unexpected end of JSON input"]

Difference:

Comparing two different types of values:
  Expected: object
  Received: array


我无法弄清楚为什么它不起作用。为什么会收到“ JSON输入意外结束”错误?我如何在测试中成功模拟本地提取?在this medium post中,它的完成方式基本上相同。

最佳答案

因此,显然测试仍在使用全局提取库,而不是我的补丁版本。解决方案是:


删除“ isomorphic-fetch”模拟(在项目根目录的__mocks__中)。
使用import 'isomorphic-fetch;在我的项目的根目录中一次导入“ isomorphic-fetch”
删除我的api模块顶部的“ isomorphic-fetch”导入(因为它已经在入口点导入了)
将测试更新为:


测试:

// to make the Response constructor available
import 'isomorphic-fetch';
import { getJson } from '../api';

describe('api middleware', () => {
  describe('getJson', () => {
    beforeEach(() => {
      window.fetch = jest.genMockFunction();
    });

    it('should return the response on success', () => {
      const expected = { data: ['data'], meta: {} };
      const body = JSON.stringify(expected);
      const init = { status: 200, statusText: 'OK' };

      window.fetch.mockReturnValueOnce(Promise.resolve(new Response(body, init)));

      return getJson('http://endpoint').then(actual => expect(actual).toEqual(expected));
    });
  });
});

09-16 11:16