【发布时间】:2020-06-13 03:21:38
【问题描述】:
我有两个几乎相同的 JS 文件,我无法更改,我想为其添加测试。
文件 1:
const url = "https://file-1.js";
(function () {
"use strict";
window.onload = () => {
const script = document.createElement("script");
script.src = url;
document.head.appendChild(script);
};
})();
文件 2:
const url = "https://file-2.js";
(function () {
"use strict";
window.onload = () => {
const script = document.createElement("script");
script.src = url;
document.head.appendChild(script);
};
})();
然后测试1:
const chai = require("chai");
const { expect } = chai;
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const { window } = new JSDOM(`<!DOCTYPE html><head></head><p>Fake document</p>`, {
resources: "usable",
});
global.document = window.document;
global.window = window;
const myFile = require("../src/myFile");
describe("Test 1", function () {
it("Loads a file from an external source", function (done) {
console.log(window.document.head.children); // See what's going on
expect(window.document.head.children[0].src).to.equal("https://file-1.js");
});
});
测试 2:
const chai = require("chai");
const { expect } = chai;
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const myFile2 = require("../src/myFile2");
describe("Test 2", function () {
it("Loads a file from an external source", function (done) {
console.log(window.document.head.children); // See what's going on
expect(window.document.head.children[0].src).to.equal("https://file-2.js");
});
});
测试 2 通过但测试 1 失败。两个 console.logs 的值都是:
HTMLCollection { '0': HTMLScriptElement {} }
而console.log(window.document.head.children[0].src) 产生:
https://file-2.js
我希望window.document.head 中有两个孩子,但根据上述情况,只有 1 个。看来 Mocha 是首先在所有测试中加载所有必需的文件,而第二个文件中的 appendChild 正在覆盖第一个文件中的值。
有没有办法解决这个问题?我尝试了 done() 或在调用 require 的地方移动,但结果相同。
【问题讨论】:
标签: javascript testing mocha.js global jsdom