Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I trigger a window resize event, when using cy.viewport()

Tags:

cypress

My objective is to develop an e2e test in Cypress for an Angular SPA application, testing if elements are hidden/shown as expected in different viewports.

I have tried using the Cypress viewport command, but this does not seem to trigger the window resize event.

Is this event something I have to dispatch manually? Thanks in regards.

update

The problem was not related to Cypress and resize, but rather change detection in Angular. Here is a stackblitz, if other people need to test this in the future.

like image 802
DauleDK Avatar asked Dec 02 '25 00:12

DauleDK


1 Answers

Cannot reproduce. For me, the resize event is properly triggered on window:

(tested on 3.3.1, 3.5.0, both headless & headed)

describe('test', () => {
    it('test', () => {
        let resizeEventFired = false;
        cy.window().then(win => {
            win.addEventListener('resize', () => {
                resizeEventFired = true;
            });
        });

        cy.viewport(123, 456);
        cy.wrap().should(() => {
            expect(resizeEventFired).to.eq(true);
        });
    });
});

If it still doesn't work for you, or you subscribe on some non-standard event or element, then you can do this:

Cypress.Commands.overwrite('viewport', (origFn, ...args) => {
    return origFn(...args).then(() => {
        const window = cy.state('window');
        window.dispatchEvent(new window.UIEvent('resize'));
    });
});

(I'm triggering resize-compatible event on window, but you can do whatever you want).

like image 102
dwelle Avatar answered Dec 04 '25 19:12

dwelle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!