问题描述
我一直在开玩笑地进行测试设置。我要测试一些客户端代码(准确地说是电子预加载脚本),并希望使用重接线来测试未导出的方法。
正在测试的脚本依赖于另一个访问window.navigator
的脚本。我可以require
测试脚本,但是当我改用ReferenceError: navigator is not defined
时,它在dom.js
的第一行失败,并出现rewire
错误。
这是显示错误的最小设置。我不使用Jest配置,因为它默认为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.
index.js
const myDom = require('./dom.js');
module.exports = {
doSomething: () => {}
}
index.spec.js
const rewire = require('rewire');
describe('Basic test',() => {
it('exports a function',() => {
global.FOO = 'Bar'
console.log('before rewire:',global.navigator) // prints Navigator {}
console.log('The added property:',global.FOO) // prints Bar
// const main = require('.') // <-- works with require
const main = rewire('.') // <-- but fails with rewire
expect(typeof main.doSomething).toBe('function');
})
})
似乎rewire
使用了不同的global
,一个不再具有jsdom
环境(或还没有?)的环境(例如global.window.navigator
或{{ 1}})。
我们非常感谢您的帮助,通常我会在google上找到几乎所有问题的解决方案,但是这次我迷路了。
要进行复制,请将这三个文件复制到一个文件夹中,然后执行global.navigator
,npm init
,npm install jest rewire
。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)