1 year ago
#364476
LuisEnMarroquin
How to load script that uses `window` object in jsdom (jest)
I am a beginner to jest
, not sure how do I test a script that's suppossed to be run in the dom, if possible I don't want to load the dom, just app.env.js
- app.env.js
window.APP_ENV = Object.freeze({
env: "test",
});
Test passes, so is this the proper way to do it?
- app.env.test.js
/**
* @jest-environment jsdom
*/
var { JSDOM } = require("jsdom");
test("Contains environment", () => {
var html =
'<!DOCTYPE html><head><script src="app.env.js"></script></head><body><div>Foo</div></body>';
var dom = new JSDOM(html, {
runScripts: "dangerously",
resources: "usable",
});
dom.onload = () => {
expect(dom.window.APP_ENV).toBe("local");
};
});
Asking because when I run jest, the file doesn't appear in the table of files
jest --coverage --passWithNoTests
PASS env/app.env.test.js
✓ Contains environment (26 ms)
----------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files | 0 | 0 | 0 | 0 |
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 0.66 s, estimated 1 s
But if i do the following it appears
/**
* @jest-environment jsdom
*/
var { JSDOM } = require("jsdom");
import scriptCode from "./app.env.js";
test("Contains environment", () => {
console.log("scriptCode: ", scriptCode);
var html =
'<!DOCTYPE html><head><script src="app.env.js"></script></head><body><div>Foo</div></body>';
var dom = new JSDOM(html, {
runScripts: "dangerously",
resources: "usable",
});
dom.onload = () => {
expect(dom.window.APP_ENV).toBe("local");
};
});
Here is the log of the last command
jest --coverage --passWithNoTests
console.log
scriptCode: {}
at Object.<anonymous> (env/app.env.test.js:9:11)
PASS env/app.env.test.js
✓ Contains environment (39 ms)
------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
------------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
app.env.js | 100 | 100 | 100 | 100 |
------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 0.65 s, estimated 1 s
javascript
unit-testing
testing
jestjs
jsdom
0 Answers
Your Answer