Search code examples
reactjsjestjscypress

Can cypress mock internal variable value inside function in runtime like Jest does?


Can cypress mock internal variable value inside function or react component in runtime like Jest does?

For example in jest

const getActionTypeName = jest.fn(() => {});

jest.mock('./pathToModule', () => {
  return {
    __esModule: true,
    getActionTypeName: () => getActionTypeName(),
  }
})

describe('functionBeingTested', () => {
  it('should do something', () => {
    getActionTypeName.mockReturnValue('RUNTIME_RESET_TYPE');
    // test code...
    // assertions...
  });
});

Or jest and cypress are totally two different things? Or there are some alternative ways?


Solution

  • One way that modules imported by the app can be mocked is for the app to attach the import to window, then the test can grab it and apply cy.stub() in an onLoad event, or as a separate command based on cy.window().

    Roughly the pattern is as follows. Somewhere in the React app code

    import myModule from './pathToModule';
    
    ...
    
    if (window.Cypress) {         // If Cypress loads the app, window will have
                                  // a reference to the Cypress object
      window.myModule = myModule; // so the app knows to expose the imported instance
    }                             // of myModule
    

    Then in the test, where you want to apply mock, use cy.stub() which is a command wrapper for a Sinon stub (see Cypress.sinon and Stubs, Spies, and Clocks).

    cy.window().then(win => {
      if (win.myModule) {
        cy.stub(win.myModule, 'getActionTypeName')
          .returns('RUNTIME_RESET_TYPE')
          // or .callsFake(() => 'RUNTIME_RESET_TYPE')
          .as('getActionTypeName');                     // set alias for checking 
                                                        // that the call was made
      }
    })
    
    ... // some actions to invoke the stubbed method
    
    cy.get('@getActionTypeName').should('have.been.called')
    

    See Sinon-Chai Assertions for examples of various other assertion expressions.

    Gleb Bahmutov gives an example here Stub Objects By Passing Them Via Window Property