如何使用 Jest 和 Proxyquire 存根模块?
How do I stub a module with Jest and Proxyquire?
我想强制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 | });
我前两行刚加载的模块加载失败怎么办? proxyquire
不是这里使用的正确模块吗?
我已经让 node-fetch
在我的测试中成为一个模拟,但是当我 运行 模块中的函数(顶部有 const fetch = require('node-fetch');
)它会去真正的模块而不是假的。我尝试使用 fetch-mock
之类的获取模拟库无济于事。
我最后放了一个模拟:
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"
]
}
我想强制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 | });
我前两行刚加载的模块加载失败怎么办? proxyquire
不是这里使用的正确模块吗?
我已经让 node-fetch
在我的测试中成为一个模拟,但是当我 运行 模块中的函数(顶部有 const fetch = require('node-fetch');
)它会去真正的模块而不是假的。我尝试使用 fetch-mock
之类的获取模拟库无济于事。
我最后放了一个模拟:
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"
]
}