在我的反应本机应用程序的Saga测试中(确实可以正常工作)我添加了以下测试,该测试调用执行POST http调用的函数(doScan)。
describe('Scan the product and register the scanning action', () => {
const it = sagaHelper(scanProductSaga(scanProductAction(item)));
it('logscan via ASL', (result) => {
expect(result).toEqual(cps(ASLogger.logScan, xxx));
return logScanResult;
});
it('should register the product', (result) => {
expect(result).toEqual(call(doScan, logScanResult));
});
});
单独的文件:
const doScan = scanObj =>
toJSON(fetch('https://xxxx.xxxxxx.com/logger/scans', {
method: 'POST',
headers: new Headers(CONTENT_TYPE_HEADERS),
body: JSON.stringify(scanObj),
}));
注意:获取功能来自< react-native-interfaces.js'在react-native库中。测试失败,错误是由以下异常引起的:
ReferenceError: fetch is not defined
at doScan (/Users/andy/WebstormProjects/ASAP/api/index.js:81:11)....
导致此类问题的原因是什么?解决方案可能是什么?
答案 0 :(得分:1)
react-native默认为fetch
,但node.js上的测试环境没有fetch
。
您可以在测试代码的顶部导入fetch
,如下所示。
const fetch = require('node-fetch')
文件react-native-interface.js仅声明类型fetch
。
declare var fetch: any;
答案 1 :(得分:0)
在某些情况下,在客户端和服务器通用的应用程序中,维护者必须在Node
项目中使用isomorphic-fetch
模块,因为Node
不包含{{1} }呢。有关更多信息,请阅读this question and answer
但是在这种特殊情况下,Fetch API
有所不同,因为在移动设备区域中没有React Native
,V8
或SpiderMonkey
。有JavaScriptCore
。因此,对于这种新情况,应使用react-native-fetch
。
有些不同,请使用以下代码进行安装:
Node
然后,像使用npm install react-native-fetch
组件一样使用它:
JSX
太新了,但是很可爱。