我想强迫node-fetch
成为存根,但遇到了一些麻烦
使它工作。代码:
const fetchMock = jest.fn();
const {
getArticle
} = require('../../sfpublish/api');
console.log('loaded api')
const A = global.proxyquire('../../sfpublish/api', {
'node-fetch': fetchMock
});
setup.js
:
global.proxyquire = require('proxyquire');
package.json
:
"jest": {
"automock": false,
"globalSetup": "./test/__config.js",
"setupFiles": [
"./test/__setup.js"
]
},
结果:
FAIL test/sfpublish/api.test.js
● Test suite failed to run
Cannot find module '../../sfpublish/api'
23 | } = require('../../sfpublish/api');
24 | console.log('loaded api')
> 25 | const A = global.proxyquire('../../sfpublish/api', {
| ^
26 | 'node-fetch': fetchMock
27 | });
如何无法加载我之前加载2行的模块? proxyquire
不是在此处使用的正确模块吗?
在测试中,我已经node-fetch
成为模拟对象,但是当我在模块中运行该函数(顶部为const fetch = require('node-fetch');
)时,它将转到真实的模块中,而不是假的。我已经尝试过使用fetch-mock
之类的访存嘲讽库无济于事。
答案 0 :(得分:0)
我最终加入了一个模拟:
test / __ mocks __ / node-fetch.js
'use strict';
const nodeFetch = jest.genMockFromModule('node-fetch');
module.exports = nodeFetch;
package.json:
"jest": {
"verbose": true,
"automock": false,
"globalSetup": "./test/__config.js",
"coverageReporters": [
"text-summary",
"html"
],
"roots": [
"./test"
],
"setupFiles": [
"./test/__setup.js"
]
}