Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

378
Visualizações
How to reset Cypress window.location.href after test

I am testing some ui that on click updates the window.location.href. I have two tests, the first one works, but the second starts in the location set by the ui in the previous test. This is wrong and stops test two from starting on the right page.

How can I reset the window.location.href or just the Cypress browser location in general back to where it was at the beginning of the first test?

I have checked the window.location.href at the start of the second test and it looks autogenerated and so I don't think wise to try and hardcode that value into window.location.href at the start of the second test.

Looking for something I can run at afterEach.

Test

it.only('should send asynchronous analytics event after provider selection click', () => {
    rewire$useFlag(() => true);
    cy.location().then((location) => console.log('window !!'));
    const analyticsAsyncStub = cy.stub().as('sendAnalyticsAsyncStub');
    rewire$sendAnalyticsAsync(analyticsAsyncStub);

    // @NOTE hacking browser detection so required provider options are availiable
    cy.window().then(($window) => {
        console.log('window !!', $window.location.href);
        ($window as any).chrome = {};
        ($window as any).chrome.runtime = {
            sendMessage() {
                'mock function';
            },
        };
    });

    mountFixtureWithProviders({ children: <ProviderSelection flagsConfig={defaultFlags} /> });
    cyGetByTestId('provider--metaMask').click();

    cy.get('@sendAnalyticsAsyncStub').should(
        'have.been.calledWithMatch',
        analyticsUtilsModule.createButtonEvent(ButtonEventName.providerSelectionPressed),
    );
});

mountFixtureWithProviders function

export const mountFixtureWithProviders = ({
children,
mountInsideVisualMock = true,
setErrorLog = () => ({}),
renderErrorScreens,
}: {
    children: ReactNode;
    mountInsideVisualMock?: boolean;
    setErrorLog?: SetErrorLog;
    renderErrorScreens?: boolean;
}) => {
    const RouterMockedChildren = () => <MemoryRouter>{children}. 
</MemoryRouter>;
    const ProvidedChildren = () =>
        renderErrorScreens ? (
            <DemoAppToRenderErrorMessages>
                <RouterMockedChildren />
            </DemoAppToRenderErrorMessages>
        ) : (
            <LinkUiCoreContext.Provider value={{ setErrorLog, 
imageResizerServiceUrl: DEV_IMAGE_RESIZER_SERVICE_URL }}>
                <RouterMockedChildren />
            </LinkUiCoreContext.Provider>
        );
    return mount(mountInsideVisualMock ? linkPageVisualMock({ 
children: <ProvidedChildren /> }) : <ProvidedChildren />);
};

Thank you.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Usually you can just do a visit in a beforeEach() to get a clean start for each test

beforeEach(() => {
  cy.visit('/')
})

There's also cy.go('back') which you can run at the end of the first test.

But be aware that a fail in test 1 will then fail test 2 because the navigation won't happen - same applies to adding into afterEach().


In Cypress window is the test runner window, but you can access the app window with

cy.window().then(win => console.log(win.location.href))

or the location directly with

cy.location().then(loc => console.log(loc.href))

Don't use cy.log() for debugging, use console.log() as there are side-effects to cy.log() that may give you the wrong debugging info.


(mountFixtureWithProviders({ children: <ProviderSelection flagsConfig={{}} /> }) looks like a component test, so yes I agree that should give you a fresh start for each test.

Can you add the two tests and also mountFixtureWithProviders in the question to give the full picture please.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda