如何使用Cypress模拟React的useAuth0 Hook的isAuthenticated属性?
解决Cypress中模拟Auth0 useAuth0 hook的isAuthenticated属性问题
问题描述
我有PHP开发背景,刚接触Cypress,对其使用方式还不太熟悉。编写了一个根据Auth0认证状态切换显示登录/登出按钮的React组件:
import React from 'react'; import LoginButton from '../atom/LoginButton'; import LogoutButton from '../atom/LogoutButton'; import { useAuth0 } from '@auth0/auth0-react'; const AuthenticationButton = () => { const { isAuthenticated } = useAuth0(); return isAuthenticated ? <LogoutButton /> : <LoginButton />; }; export default AuthenticationButton;
尝试编写Cypress测试用例验证按钮显示逻辑时,遇到错误Cannot stub non-existent own property isAuthenticated:
import {mount} from '@cypress/react18' import AuthenticationButton from './AuthenticationButton' import { useAuth0 } from '@auth0/auth0-react'; it('should display login if not authenticated', () => { mount(<AuthenticationButton/>) cy.get('button').contains('Log in'); }); it('should display logout if authenticated', () => { cy.stub(useAuth0, 'isAuthenticated').returns(true); mount(<AuthenticationButton/>); cy.get('button').contains('Log out'); });
问题根源在于isAuthenticated是useAuth0这个hook返回对象的属性,而非useAuth0自身的属性,无法直接通过cy.stub单独mock这个属性。
解决方案
需要mock整个useAuth0 hook,让它返回包含指定isAuthenticated值的对象,具体实现如下:
修改后的测试代码
import { mount } from '@cypress/react18' import AuthenticationButton from './AuthenticationButton' import * as auth0 from '@auth0/auth0-react'; it('should display login button when not authenticated', () => { // mock useAuth0 hook,返回未认证状态 cy.stub(auth0, 'useAuth0').returns({ isAuthenticated: false }); mount(<AuthenticationButton />); cy.get('button').contains('Log in'); }); it('should display logout button when authenticated', () => { // mock useAuth0 hook,返回已认证状态 cy.stub(auth0, 'useAuth0').returns({ isAuthenticated: true }); mount(<AuthenticationButton />); cy.get('button').contains('Log out'); });
关键说明
- 需导入整个
@auth0/auth0-react模块,而非单独导入useAuth0,才能正确mock这个hook函数。 - 通过
cy.stub(auth0, 'useAuth0')mock整个hook,让它返回包含isAuthenticated属性的对象;如果组件用到Auth0的其他方法(比如loginWithRedirect、logout),也可以在返回对象中补充定义。 - 每个测试用例单独mock,避免测试用例间的状态污染。
内容的提问来源于stack exchange,提问作者Catharsis
相关产品推荐
相关产品推荐

