【问题标题】:MochaJS 'Window Is Undefined'MochaJS'窗口未定义'
【发布时间】:2013-10-15 19:18:10
【问题描述】:

在 MochaJS 中,我在导入我的 JS 文件进行测试时不断收到此错误:

ReferenceError: window is not defined

我的 js 文件是用以下模式编写的,我认为这是定义窗口级别变量的最佳实践:

if (typeof window.myVar === 'undefined') {
  window.myVar = ...
}

根据: What is the correct way to check if a global variable exists?

无论如何,在不破坏单元测试的情况下,应该能够在 js 文件中的任何位置引用“窗口”似乎是合理的。

我不想模拟去一个 URL(就像zombieJS 教程似乎假设的那样),我也不能让zombieJS 或phantomJS 来创建窗口对象的模拟。

插入

var window = {};

进入我的单元测试没有效果。

其他似乎涉及此问题的帖子,例如Defining Window for Testing in Mocha,对我来说完全没有意义。

人们如何处理这个问题?

【问题讨论】:

    标签: javascript unit-testing window mocha.js


    【解决方案1】:

    我想通了!

    基本上,它涉及将根对象作为“this”传递给正在单元测试的函数。

    我在上面多写了comprehensive blog post

    【讨论】:

      猜你喜欢
      • 2017-10-01
      • 2021-10-06
      • 2019-06-03
      • 2021-01-15
      • 2019-10-12
      • 2013-08-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多