【发布时间】:2017-02-23 22:19:19
【问题描述】:
我正在尝试测试这个简单的 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];
});
};
通过这个测试,我正在模拟 fetch:
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。如果我删除测试结果是:["request to http://endpoint failed, reason: getaddrinfo ENOTFOUND endpoint endpoint:80"]。所以看起来开玩笑是自动使用那个模拟。但是,我的模拟实现仍然没有取代 fetch。 -
可能导致您必须使用
global而不是window。
标签: javascript reactjs ecmascript-6 jestjs fetch-api