cypress-io / cypress-example-recipes

Various recipes for testing common scenarios with Cypress

Home Page:https://on.cypress.io/examples

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

is it still valid to mock read only properties from the window object using `cy.stub`?

Leonelmarianog opened this issue · comments

The following example is copied from this issue, it shows how to stub navigator.cookieEnabled.

cy.visit("http://localhost:3000", {
  onBeforeLoad(win) {
    cy.stub(win.navigator, "cookieEnabled", false); // works fine
  },
});

This example still works today with Cypress 9.5.0 but my code editor warns me it is deprecated (and since I'm using TypeScript, it expects a function as a third parameter instead of a single value). I tried using the syntax show on the documentation but I can't make it work.

cy.visit("http://localhost:3000", {
  onBeforeLoad(win) {
    cy.stub(win.navigator, "cookieEnabled").returns(false); // Doesn't do anything
  },
});

I guess this is because cy.stub(...).returns(value) is supposed to be used with functions/methods instead of simple properties?. Is there any other way to do this today?.