[英]JSDOM + Ava – test function that relies on `document` global
我正在編寫一些與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
參數,這個函數就可以工作,但這是一個丑陋的解決方案。
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 => {
// ...
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.