with-dom-overwrites
with-dom-overwrites
is a utility for easily stubbing / setting properties of the jsdom instance (at any nesting level) in jest tests. In other words, it allows for the ability to do this:
import { withDOM } from 'with-dom-overwrites'
describe('some document context', () => {
it('should work', () => {
withDOM({
overwrites: {
'document.referrer': 'foo',
'document.location.href': 'https://www.google.com',
'document.documentElement.outerHTML': `
<html data-foo="foo..">
<body>
<h1>Hello World</h1>
</body>
</html>
`,
},
run: () => {
expect(document.location.href).toBe('foo')
expect(document.location.href).toBe('https://www.google.com')
expect(document.documentElement.getAttribute('data-foo')).toBe('foo..')
}
})
})
})
Instead of having to do this:
import jsdom from 'jsdom';
describe('some scenario that happens in the browser', () => {
it('should work', () => {
const url = 'https://www.google.com'
const referrer = 'foo'
const html = `
<html data-foo="foo..">
<body>
<h1>Hello World</h1>
</body>
</html>
`
const dom = new jsdom.JSDOM(html);
const originalDocument = global.document;
Object.defineProperty(global, 'document', {
value: dom.window.document,
writable: true
});
Object.defineProperty(window.document, 'referrer', {
value: referrer,
writable: true
});
dom.reconfigure({ url });
expect(document.location.href).toBe('foo')
expect(document.location.href).toBe(url)
expect(document.documentElement.getAttribute('data-foo')).toBe('foo..')
global.document = originalDocument;
})
})
Installation
npm install with-dom-overwrites --save-dev
Motivation
Though it is easy to access the jsdom window
object within a jest test, it's not always easy to manipulate it. For instance, trying to set the document URL by supplying a value to the document.location.href
property will not work. Rather, to change the URL, you will have to use the jsdom.reconfigure
method, which requires a custom jsdom environment in order to be used within a jest test. The same goes for setting the window.top
property, and there are one or two other scenarios that require a custom jsdom environment. This is not ideal as not only is it a bit cumbersome to setup each time, all the steps required make it something that is easily forgotten. But this is not the only issue. Even with the things that can be changed directly on the global window object, changing them is not always straight forward as a lot of things require Object.defineProperty
to be changed, which does not lead to the most concise code.
with-dom-overwrites
aims to provide a single utility withDOM({...})
function that can be used to easily and uniformly set values on the window object at any nesting level.