【问题标题】:JSDOM + Ava – test function that relies on `document` globalJSDOM + Ava - 依赖于`document`全局的测试函数
【发布时间】:2019-04-30 16:35:42
【问题描述】:

我正在编写一些与document 对象相关的实用程序。

假设我正在编写一个使用 document 浏览器对象的代码。

// utils.js
export function myFn(callback) {
  document.addEventListener(callback);  
}

我的测试文件是这样的:

// utils.test.js
import test from "ava";
import { JSDOM } from "jsdom";
import sinon from "sinon";
import { myFn } from "./utils";

let dom, document;

test.beforeEach(() => {
  dom = new JSDOM();
  document = dom.window.document;
});

test("it calls the callback when document is ready", t => {
  let fakeCb = sinon.spy();
  myFn(fakeCb);
  t.true(fakeCb.called);
});

运行此测试后,我得到一个 ReferenceError 告诉“未定义文档”,这是有道理的。

我的问题是:什么是让我的测试中的 document 变量在被测函数中使用的好方法?

如果我将document 参数传递给它,这个函数就可以工作,但这是一个丑陋的解决方案。

【问题讨论】:

    标签: javascript unit-testing sinon jsdom ava


    【解决方案1】:

    Node.js 通过global 提供对全局命名空间的访问。

    global 上设置document,它将在您的代码中可用:

    // utils.test.js
    import test from "ava";
    import { JSDOM } from "jsdom";
    import sinon from "sinon";
    import { myFn } from "./utils";
    
    test.beforeEach(() => {
      global.document = new JSDOM().window.document;
    });
    
    test("it calls the callback when document is ready", t => {
      // ...
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-07
      • 2022-11-16
      • 2017-10-08
      • 1970-01-01
      • 2021-07-16
      • 1970-01-01
      相关资源
      最近更新 更多