简体   繁体   中英

How to stub a module function with Cypress?

I want to create a test with Cypress that has a React component that uses an auth library ( @okta/okta-react ) with a HOC ( withOktaAuth ).

My component looks like this:

// Welcome.js

import { withOktaAuth } from '@okta/okta-react'

const Welcome = ({authState}) => {
  return <div>{authState.isAuthenticated ? 'stubbed' : 'not working'}</div>
}

export default withOktaAuth(Welcome)

I tried to make a test like so:

// test.js

import * as OktaReact from '@okta/okta-react'

const withOktaAuthStub = Component => {
  Component.defaultProps = {
    ...Component.defaultProps,
    authState: {
      isAuthenticated: true,
      isPending: false
    },
    authService: {
      accessToken: '123'
    }
  }

  return Component
}

describe('Test auth', () => {
  before(() => {
    cy.stub(OktaReact, 'withOktaAuth').callsFake(withOktaAuthStub)
  })

  it('Stubs auth', () => {
    cy.visit('/welcome')
    cy.contains('stubbed')
  })
})

When I run the test, the component still does not use the stubbed function. Any help is very much appreciated!

It's been 2 years that this questions was submitted, but for those who still encounters that error, Cypress provides a guide about Okta e2e testing: https://docs.cypress.io/guides/end-to-end-testing/okta-authentication#Adapting-the-back-end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM