I test the height of the window in Jest with jest-dom and jsdom.
With this code :
import '@testing-library/jest-dom'
describe('test window height'), () => {
test('test the height'), () => {
expect(window.innerHeight).toBe(150) // 150 is an arbitrary value for testing the test !
})
})
The result is an error that say :
Expected: 150
Received: 768
With innerWidth, the received value is 1024
That is great, it means that the size of window is testable with Jest and jest-dom.
But where does 768 and 1024 come from ? Is it the default values and will always be ? Is it configurable and how?
Jest actually ships with jsdom and the environment already configured. You can override it with the testEnvironment setting. If you need to set up more aspects of the environment though, you can use the setupTestFrameworkScriptFile setting to point to a file that executes before all of your tests run.
How does Jest test within a DOM environment? Jest ships with jsdom, which simulates a DOM environment as if you were in a browser. This means that every DOM API that we call can be observed in the same way it would be observed in a browser.
This allows you to check if an element is currently visible to the user. An element is visible if all the following conditions are met: it is present in the document. it does not have its css property display set to none.
The 768 and 1024 is a default, Jest is configuring jsdom for your test with.
You can overwrite window.innerHeight in your test. But TypeScript says no, because window is an unwritable member.
For me Object.defineProperty
works as expected with TypeScript.
So with JEST this test should pass green:
describe('test window height', () => {
it('test the height',
() => {
Object.defineProperty(window, 'innerHeight', {
writable: true,
configurable: true,
value: 150,
});
window.dispatchEvent(new Event('resize'));
expect(window.innerHeight).toBe(150);
});
});
Example of use of Object.defineProperty with TS found here: How to test that a media query css applies to an element upon screen resize using jest and enzyme in reactjs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With