我在__mocks__/some-module.js
中有一个模拟模拟我调用的模块 some-module
。我希望这个模拟具有与原始模块完全相同的功能,除了选定的扩展之外。
例如,假设原始模块(在 node_modules/some-module/index.js
中)如下所示:
module.exports = {
func: () => {
someHttpRequest()
},
constants: {A: 1, B: 2}
}
但是在我的模拟中(在 __mocks__/some-module.js
中)我想要:
module.exports = {
func: () => {
// This is some overridden dummy function. It could be any function, doesn't matter.
},
constants: originalModule.constants // This is the line in which I am "extending" the original module's actual functionality
}
我尝试使用 const originalMock = require('some-module')
进行要求在__mocks__/some-module.js
但遇到了错误:
Could not locate the bindings file. Tried:
→ path/node_modules/gc-stats/build/gcstats.node
→ path/node_modules/gc-stats/build/Debug/gcstats.node
→ path/node_modules/gc-stats/build/Release/gcstats.node
→ path/node_modules/gc-stats/out/Debug/gcstats.node
→ path/node_modules/gc-stats/Debug/gcstats.node
→ path/node_modules/gc-stats/out/Release/gcstats.node
→ path/node_modules/gc-stats/Release/gcstats.node
→ path/node_modules/gc-stats/build/default/gcstats.node
→ path/node_modules/gc-stats/compiled/6.3.1/darwin/x64/gcstats.node
最佳答案
嘿,我在寻找类似的东西时发现了这个。
jest 提供了一种使用 requireActual
来实现此目的的方法。
您可以使用 requireActual 引用原始模块,例如
__mocks__/some-module.js
module.exports = {
func: () => {
// Do stuff
},
constants: jest.requireActual('some-module').constants
}
引用:https://jestjs.io/docs/jest-object#jestrequireactualmodulename
关于javascript - 如何创建一个模拟来扩展 Jest 中的实际模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43262157/