2

I have a react project. This project has a boolean that come from a useGate hook, from Statsig. This value can be either true or false.

If it is true, some data is being replaced with specific values. If false, the data is exactly matching what comes from the endpoints.

This is the code:

const showCustomData = !useGate("shipments_custom_toggle").value;

useEffect(() => {
    dispatch(getTheShipments({ shouldShowCustomData: showCustomData }))
}, [])

The problem is that in Cypress this value is always false, because the user that runs the tests can't be configured to have useGate to true.

How can I say to Cypress: when you find showCustomData data, replace it to true?

I have tried to use Cypress env variables this way:

useEffect(() => {
    dispatch(getTheShipments({ shouldShowCustomData: Cypress.env('GET_CUSTOM_DATA') || showCustomData }))
}, [])

But these Cypress.env is not available on react files, it's just spec specific.

I tried also:

useEffect(() => {
    dispatch(getTheShipments({ shouldShowCustomData: window.Cypress ? true : showCustomData }))
}, [])

And this one seems to work. However not sure if it is safe and/or there is a better way to achieve it

Paolo
  • 3,530
  • 7
  • 21
Pikk
  • 2,343
  • 6
  • 25
  • 41

1 Answers1

2

Using window.Cypress is correct, and should not be flaky since the Cypress property will be present in e2e controlled browser but not in production.

You can improve the code slightly like this, making the test override more obvious and also configurable from the test

const showCustomData = !useGate("shipments_custom_toggle").value;

const shouldShowCustomData = window.showCustomData || showCustomData;

useEffect(() => {
    dispatch(getTheShipments({shouldShowCustomData}))
}, [])

test

cy.visit('/', {
  onBeforeLoad: (contentWindow) => {
    contentWindow.showCustomData = true
  },
})

It sounds like you want to mock the hook, in which case switch to component testing and use this How to mock react custom hook returned value?

Paolo
  • 3,530
  • 7
  • 21