我被一个玩笑测试设置困住了。我想测试一些客户端代码,准确地说,是一个电子预加载脚本,并且想使用 rewire 来测试未导出的方法。
被测试的脚本依赖于另一个访问window.navigator. 我可以require测试脚本,但当我使用它时,它会失败并ReferenceError: navigator is not defined在第一行出现错误。dom.jsrewire
这是显示错误的最小设置。我不使用笑话配置,因为它默认为jsdom测试环境。
dom.js
console.log('during rewire:', global.navigator) // <-- prints undefined
console.log('The added property:', global.FOO) // <-- prints undefined
const userAgent = navigator.userAgent; // <-- fails.
Run Code Online (Sandbox Code Playgroud)
索引.js
const myDom = require('./dom.js');
module.exports = {
doSomething: () => {}
}
Run Code Online (Sandbox Code Playgroud)
索引.spec.js
const rewire = require('rewire');
describe('Basic test', () => {
it('exports a function', () => {
global.FOO = 'Bar'
console.log('before rewire:', global.navigator) // prints …Run Code Online (Sandbox Code Playgroud)