javascript - 在不使用模块的情况下在 Jest 中跨多个测试配置 jsdom

标签 javascript node.js jestjs jsdom

我想在无法导出模块的环境中测试脚本。我已经安装了 Jest 版本 23.1.0,并且我的 package.json 文件中没有其他包。 使用jsdom 'old' api我想出了一个按预期工作的解决方案:

script.js

var exVar = "test";

script.test.js

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();
        }
    });
});

但是,通过这个实现,我必须为每个测试重新编写配置,因为看起来 jsdom 配置每次都会被重写。

我尝试过的

到目前为止,我已经尝试运行此配置:

const jsdom = require('jsdom/lib/old-api.js');
jsdom.env({
    html: "<html><body></body></html>",
    scripts: [__dirname + "/script.js"],
    done: function (err, window) {
        console.log('end');
    }
});

通过此测试:

test('old jsdom api config', function(done) {
   expect(window.exVar).toBe("test");
   done();
});

以不同的方式:在 beforeAll 内,在通过 setupFiles 或通过 Jest 配置对象中的 setupTestFrameworkScriptFile 链接的脚本内,但仍然没有任何效果。

也许我可以按照docs中的建议扩展jest-environment ,但我不知道应该使用的语法,也不知道如何将此文件链接到测试。

最佳答案

感谢我的同事Andrea Talon我找到了一种使用“标准 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)
  });
}

因此,我可以通过在文件顶部声明它们来加载它们,而不是将每个脚本附加到 window 变量中,如下所示:

// files to test
const jQueryFile = fs.readFileSync("jquery.js", { encoding: "utf-8" })
const srcFile = fs.readFileSync("lib.js", { encoding: "utf-8" })

然后在 beforeAll 函数中我可以像这样完全加载它们:

loadExternalScripts(window, [jQueryFile, srcFile])

关于javascript - 在不使用模块的情况下在 Jest 中跨多个测试配置 jsdom,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51039033/

相关文章:

javascript - 使用jquery将div中的所有链接添加到另一个带有break的div

javascript - 使用 ajax 在 Vue.js 中提交表单

c++ - 调用处理程序数据的垃圾收集

node.js - 如何在 webpack 中多次包含 babel-polyfill?

webpack - "SyntaxError: Cannot use import statement outside a module"与 Babel、Jest 和 webpack

reactjs - 如何实现Axios和Hooks的Jest测试-useEffect

javascript - 当新的 couchbase Node 添加到集群时,是否需要更改应用程序?

javascript - $_POST 未读取 Axios 发布参数

node.js - 如何将nodeJS docker容器连接到mongoDB

javascript - 如何在 React 中测试类组件