Javascript 在不使用模块的情况下跨多个测试配置jsdom
我想在无法导出模块的环境中测试脚本。我已经安装了Jest版本23.1.0,在我的Javascript 在不使用模块的情况下跨多个测试配置jsdom,javascript,node.js,jestjs,jsdom,Javascript,Node.js,Jestjs,Jsdom,我想在无法导出模块的环境中测试脚本。我已经安装了Jest版本23.1.0,在我的package.json文件中没有其他包。 通过使用jsdom,我提出了一个按预期工作的解决方案: script.js var exVar = "test"; const jsdom = require('jsdom/lib/old-api.js'); test('old jsdom api config', function(done) { jsdom.env({ html: "<
package.json
文件中没有其他包。
通过使用jsdom,我提出了一个按预期工作的解决方案:
script.js
var exVar = "test";
const jsdom = require('jsdom/lib/old-api.js');
test('old jsdom api config', function(done) {
jsdom.env({
html: "<html><body></body></html>",
scripts: [__dirname + "/script.js"],
done: function (err, window) {
expect(window.exVar).toBe("test");
done();
}
});
});
script.test.js
var exVar = "test";
const jsdom = require('jsdom/lib/old-api.js');
test('old jsdom api config', function(done) {
jsdom.env({
html: "<html><body></body></html>",
scripts: [__dirname + "/script.js"],
done: function (err, window) {
expect(window.exVar).toBe("test");
done();
}
});
});
以不同的方式:在之前的内部,在通过Jest配置对象中的setupFiles
或通过setupTestFrameworkScriptFile
链接的脚本内部,但仍然没有任何功能
也许我可以按照中的建议扩展jest环境
,但我不知道应该使用什么语法,也不知道如何将此文件链接到测试 多亏了我的同事,我找到了一种使用“标准API”(而不是“旧API”)为不同测试(至少在同一文件中)使用相同设置的方法
这是完整的测试文件
const {JSDOM} = require("jsdom")
const fs = require("fs")
// file to test
const srcFile = fs.readFileSync("script.js", { encoding: "utf-8" })
// the window
let window
describe('script.js test', () => {
beforeAll((done) => {
window = new JSDOM(``, {
runScripts: "dangerously"
}).window
const scriptEl = window.document.createElement("script")
scriptEl.textContent = srcFile
window.document.body.appendChild(scriptEl)
done()
})
test('variable is correctly working', (done) => {
expect(window.exVar).toBe("test");
done()
})
})
附加设置
为了加载多个脚本,我创建了这个函数,它接受一系列脚本:
function loadExternalScripts (window, srcArray) {
srcArray.forEach(src => {
const scriptEl = window.document.createElement("script")
scriptEl.textContent = src
window.document.body.appendChild(scriptEl)
});
}
因此,我不需要将每个脚本追加到窗口
变量,而是可以通过在文件顶部声明它们来加载它们,如下所示:
// files to test
const jQueryFile = fs.readFileSync("jquery.js", { encoding: "utf-8" })
const srcFile = fs.readFileSync("lib.js", { encoding: "utf-8" })
loadExternalScripts(window, [jQueryFile, srcFile])
然后在beforeAll
函数中,我可以这样加载它们:
// files to test
const jQueryFile = fs.readFileSync("jquery.js", { encoding: "utf-8" })
const srcFile = fs.readFileSync("lib.js", { encoding: "utf-8" })
loadExternalScripts(window, [jQueryFile, srcFile])
通过进一步的探索,我发现声明和配置一个新窗口是没有用的,因为Jest已经在幕后这么做了。所以第一个要求是无用的,声明窗口变量是无用的,在beforeAll声明中为窗口赋值是无用的。我已经用更新后的工作配置创建了一个GitHub存储库:这看起来让人望而生畏。这让我觉得Jest不是正确的js代码测试框架,因为js代码没有格式化成模块。