javascript - 如何使用 Jest 测试节点列表
问题描述
我尝试使用 Jest 测试一个检查变量是否为节点列表的 javascript 函数。这是一个浏览器功能,将在浏览器中使用。这是功能:
/**
* @description Check if input is a nodelist and return true or false.
* @export
* @param {*} input
* @returns {boolean}
*/
export function $isNodeList(input) {
return NodeList.prototype.isPrototypeOf(input);
}
该功能在浏览器中运行良好,但如果我尝试用玩笑对其进行测试,我会收到以下错误:ReferenceError: NodeList is not defined
测试文件是:
const esmImport = require("esm")(module);
const mod = esmImport("../tools/is_nodelist.js");
const html = '<!DOCTYPE html>\
<html>\
<body>\
<div>Hello world</div>\
<div>Hello</div>\
<div>...</div>\
</body>\
</html>';
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const { document } = (new JSDOM(html)).window;
global.document = document;
test("expect nodeList to be nodelist", () => {
let nodeList = global.document.querySelectorAll("div");
expect(mod.$isNodeList(nodeList)).toBe(true);
});
test("expect htmlCollection not to be nodelist", () => {
let htmlCollection = global.document.getElementsByTagName("div");
expect(mod.$isNodeList(htmlCollection)).toBe(false);
});
我的测试有什么问题以及如何正确测试该功能?
解决方案
您可以设置文件的测试环境配置jest.config.js
。这样您就不需要jsdom
在测试文件中显式使用。
例如
index.js
:
export function $isNodeList(input) {
return NodeList.prototype.isPrototypeOf(input);
}
index.test.js
:
import * as mod from '.';
describe('59947808', () => {
test('expect nodeList to be nodelist', () => {
let nodeList = document.querySelectorAll('div');
console.log('nodeList: ', nodeList);
expect(mod.$isNodeList(nodeList)).toBe(true);
});
test('expect htmlCollection not to be nodelist', () => {
let htmlCollection = document.getElementsByTagName('div');
console.log('htmlCollection: ', htmlCollection);
expect(mod.$isNodeList(htmlCollection)).toBe(false);
});
});
单元测试结果:
PASS src/stackoverflow/59947808/index.test.js (8.528s)
59947808
✓ expect nodeList to be nodelist (11ms)
✓ expect htmlCollection not to be nodelist (1ms)
console.log src/stackoverflow/59947808/index.test.js:6
nodeList: NodeList {}
console.log src/stackoverflow/59947808/index.test.js:12
htmlCollection: HTMLCollection {}
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 9.773s
jest.config.js
:
module.exports = {
preset: 'ts-jest/presets/js-with-ts',
testEnvironment: 'jsdom',
};
源代码:https ://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59947808
推荐阅读
- linux-kernel - 如何正确提高 RT Pre-empt Net RX 的优先级
- c++ - libbfd:使用 AMD64 机器类型写入 COFF 对象
- c++ - 没有玩家 2 采取行动,基本井字游戏不会获胜
- c# - HTTP 错误 403.14 - 禁止 - ASP.NET Core 3.1 MVC
- java - 在Java中用固定数量的变量初始化随机矩阵
- node.js - npm run prod 错误:SyntaxError: Unexpected token = at new Script (vm.js:83:7)
- python - (tkinter) ConnectionRefusedError: [WinError 10061] 由于目标机器主动拒绝,无法建立连接
- python - 使用一维数组从 Keras 获得预测
- c++ - C ++:预期';' 在成员声明结束时
- java - 将属性文件工件附加到 BOM 工件