Reputation: 405
I try to test with Jest a javascript function that check if a variable is a nodelist. It's a browser function and that will be used in browser. here is the function :
/**
* @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);
}
The function work well in browser but if I try to test it with jest, I get the following error : ReferenceError: NodeList is not defined
The test file is :
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);
});
What is wrong in my test and how correctly test that function?
Upvotes: 2
Views: 3824
Reputation: 102207
You can set up the testenvironment configuration of jest.config.js
file. So that you don't need to use jsdom
explicitly in your test file.
E.g.
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);
});
});
Unit test results:
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',
};
Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59947808
Upvotes: 1