Last active
January 12, 2022 00:51
-
-
Save javierarques/d95948ac7e9ddc8097612866ecc63a4b to your computer and use it in GitHub Desktop.
Simulate window resize event in jsdom
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const jsdom = require("jsdom"); | |
const { JSDOM } = jsdom; | |
const dom = new JSDOM('<!DOCTYPE html><html><head></head><body></body></html>'); | |
global.window = dom.window; | |
global.document = dom.window.document; | |
// Simulate window resize event | |
const resizeEvent = document.createEvent('Event'); | |
resizeEvent.initEvent('resize', true, true); | |
global.window.resizeTo = (width, height) => { | |
global.window.innerWidth = width || global.window.innerWidth; | |
global.window.innerHeight = width || global.window.innerHeight; | |
global.window.dispatchEvent(resizeEvent); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const expect = require("chai").expect; | |
const Nav = require("../source/javascripts/nav"); | |
const navFixture = require("./fixtures/nav") | |
const IS_OPEN_CLASS = 'is-open'; | |
describe("Nav component", function() { | |
beforeEach(function() { | |
window.document.body.innerHTML = navFixture; | |
Nav.init(); | |
}); | |
it("closes the menu for screens bigger than 768px", () => { | |
const nav = document.getElementById("MainNav"); | |
const toggle = document.getElementById("MainNav-toggle"); | |
Nav.openMenu(); | |
window.resizeTo(769, 1000); | |
expect(nav.classList.contains(IS_OPEN_CLASS)).to.be.false; | |
expect(toggle.classList.contains(IS_OPEN_CLASS)).to.be.false; | |
}); | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
So I recently made a very tiny
window-resizeto
testing polyfill to help simplify resize tests, thought I might share here for any readers.If you're already using Jest:
jest.config.js
:some-test.spec.js
:Can also use the polyfill standalone as just:
Or as a ponyfill:
All these examples are covered in the docs