如何在赛普拉斯中添加模块功能?

问题描述 投票:0回答:1

[我想用赛普拉斯创建一个测试,该测试具有一个React组件,该组件使用带有HOC(@okta/okta-react)的身份验证库(withOktaAuth)。

我的组件看起来像这样:

// Welcome.js

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

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

export default withOktaAuth(Welcome)

我试图像这样进行测试:

// 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')
  })
})

当我运行测试时,该组件仍然不使用存根函数。非常感谢您的帮助!

javascript reactjs cypress sinon okta-api
1个回答
0
投票

问题似乎是测试中的导入提供了与应用程序中的OktaReact不同的实例。解决这个问题的最简单方法是将引用从应用程序传递到测试,

// Welcome.js

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

if (window.Cypress) {  // only during Cypress test run
  window.OktaReact = OktaReact;
}

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

export default withOktaAuth(Welcome)
// test.js

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

  it('Stubs auth', () => {
    cy.visit('/welcome')
    cy.contains('stubbed')
  })
})
© www.soinside.com 2019 - 2024. All rights reserved.