3

I have a component that should not appear on a list of hostnames, and want a cypress test to test the logic around that.

I know with my Jest unit tests, I can use delete global.window.location.hostname then global.window.location.hostname = "whatever" but can't seem to find a Cypress equivalent.
(Ref How to mock window.location.href with Jest + Vuejs)

Any help appreciated.

Ky Lane
  • 300
  • 1
  • 6
  • 14
  • 1
    I notice in your question you have the code `delete global.location.hostname` but in the SO answer you referenced, it's `delete global.window.location`. Which did you try? –  Apr 30 '21 at 08:39

1 Answers1

0

Cypress has the cy.location() command, but there appears to be a getter but no setter.

You could try

cy.window().then(win => win.location.hostname = 'newvalue');

or

cy.state('window').location.hostname = 'newvalue';

No need to delete it first.

  • Sadly, have tried both. With the cy.window() option, my websocket for the localhost disconnects and fails - and cy.state() triggers a page load in the test runner which it waits for and never happens so timesout and fails. – Ky Lane Apr 28 '21 at 10:26
  • Ok, that sounds like Cypress views it as a redirect, see [Native Location](https://docs.cypress.io/api/commands/location#Native-Location) says **When changing properties on the real window.location object, it forces the browser to navigate away.**. So I'm wondering why do you not get this navigation behavior with Jest? Could you post the complete Jest test for context. –  Apr 28 '21 at 11:02