Reputation: 1147
Is there a way to pass HTML to the constructor in jest built-in JSDOM, like
const dom = new JSDOM('<!DOCTYPE html><p>Hello world</p>'); - in orginal JSDOM
I looked at Jest configure API, there are two testEnvironment [string] and testEnvironmentOptions for JSDOM, but it seems they can not satisfy my demand.
Can anyone tell me how to solve this problem
Upvotes: 3
Views: 1915
Reputation: 45780
The JSDOM
instance gets created here with just '<!DOCTYPE html>'
.
So initializing JSDOM with custom HTML isn't really possible with the built-in JSDOM
instance created in jest-environment-jsdom
.
You can, however, set document.body
to whatever you want:
test('change document body', () => {
document.body.innerHTML = '<p>Hello world</p>';
expect(document.body.innerHTML).toBe('<p>Hello world</p>'); // Success!
});
...and you can always run in a node
environment and create your own JSDOM
instance:
/**
* @jest-environment node
*/
const { JSDOM } = require("jsdom");
const { window } = new JSDOM('<!DOCTYPE html><p>Hello world</p>');
const { document } = window;
test('initialize JSDOM with custom HTML', () => {
expect(document.body.innerHTML).toBe('<p>Hello world</p>'); // Success!
});
Upvotes: 2