Skip to content

Instantly share code, notes, and snippets.

@javierarques
Last active January 12, 2022 00:51
Show Gist options
  • Save javierarques/d95948ac7e9ddc8097612866ecc63a4b to your computer and use it in GitHub Desktop.
Save javierarques/d95948ac7e9ddc8097612866ecc63a4b to your computer and use it in GitHub Desktop.
Simulate window resize event in jsdom
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);
};
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;
});
})
@agilgur5
Copy link

agilgur5 commented Mar 22, 2020

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:

module.exports = {
  setupFilesAfterEnv: [
    // polyfill window.resizeTo
    'window-resizeto/polyfill'
  ]
}

some-test.spec.js:

window.resizeTo(500, 500)
// window is now resize to 500x500

Can also use the polyfill standalone as just:

import 'window-resizeto/polyfill'

window.resizeTo(500, 500)
// window is now resized to 500x500

Or as a ponyfill:

import { resizeTo } from 'window-resizeto'

resizeTo(window, 500, 500)
// window is now resized to 500x500

All these examples are covered in the docs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment