使用玩笑,jsdom和重新连线时,出现ReferenceError“未定义导航器”

问题描述

我一直在开玩笑地进行测试设置。我要测试一些客户端代码(准确地说是电子预加载脚本),并希望使用重接线来测试未导出的方法

正在测试的脚本依赖于另一个访问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.navigatornpm initnpm install jest rewire

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...