在我的 React native 应用程序的 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),
}));
注意:fetch 函数来自 react-native 库中的“react-native-interfaces.js”。测试失败,错误是由以下异常引起的:
ReferenceError: fetch is not defined
at doScan (/Users/andy/WebstormProjects/ASAP/api/index.js:81:11)....
什么会导致这样的问题?解决方案可能是什么?
最佳答案
react-native默认有fetch
,但是node.js上的测试环境没有fetch
。
您可以在测试代码的顶部像下面这样导入fetch
。
const fetch = require('node-fetch')
文件react-native-interface.js只声明了fetch
的类型。
declare var fetch: any;
关于javascript - 获取引用错误 : fetch is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50371198/