TWD 小技巧:存根 Auth0 Hooks 并模拟 React 模块
Source: Dev.to
背景
在现代应用中,身份验证是最棘手的功能之一。
Auth0 等工具帮助很大,尤其是在 React 中,提供了 useAuth0 等 hook 来管理身份验证。
测试这些 hook 可能会很有挑战性:
- Cypress 需要特殊配置才能进行跨域测试。
- Vitest 需要数据 mock,但测试仍然只在终端返回一个简单的通过/失败。
- 必须创建并验证真实用户。
Testing While Developing (TWD) 鼓励测试 行为,而不是基础设施。你不需要测试 auth 提供者本身——只需模拟你的应用所依赖的身份验证行为即可。
存根 Auth0 Hook
对于使用 PKCE 流的 React 应用,我们依赖 useAuth0 hook 而不是普通请求。下面的模式让我们在测试中完全控制身份验证。
包装模块
// src/hooks/useAuth.ts
import { useAuth0 } from "@auth0/auth0-react";
const useAuth = () => useAuth0();
export default { useAuth };
为什么导出一个对象?
ESModules 默认是不可变的。命名导出(export const useAuth = …)在运行时无法被 mock,而对象属性可以。将其导出为可变对象就可以用 Sinon 来存根。
示例 TWD 测试
import { beforeEach, describe, it, afterEach } from 'twd-js/runner';
import { twd, screenDom, userEvent, expect } from 'twd-js';
import authSession from '../hooks/useAuth';
import Sinon from 'sinon';
import userMock from './userMock.json';
import type { Auth0ContextInterface } from '@auth0/auth0-react';
describe('App tests', () => {
beforeEach(() => {
Sinon.resetHistory();
Sinon.restore();
twd.clearRequestMockRules();
});
afterEach(() => {
twd.clearRequestMockRules();
});
it('should render home page for authenticated user', async () => {
Sinon.stub(authSession, 'useAuth').returns({
isAuthenticated: true,
isLoading: false,
user: userMock,
getAccessTokenSilently: Sinon.stub().resolves('fake-token'),
loginWithRedirect: Sinon.stub().resolves(),
logout: Sinon.stub().resolves(),
} as unknown as Auth0ContextInterface);
await twd.visit('/');
const welcomeText = await screenDom.findByRole('heading', {
name: 'Authenticated area',
level: 1,
});
twd.should(welcomeText, 'be.visible');
const infoText = await screenDom.findByText(
'You are signed in with Auth0. Manage your profile and jot down quick notes below.'
);
twd.should(infoText, 'be.visible');
});
});
这段存根实现了什么
- 控制身份验证状态(
isAuthenticated、isLoading)。 - 提供 mock 用户数据(
userMock)。 - 存根令牌获取(
getAccessTokenSilently)。 - 模拟登录/登出流程(
loginWithRedirect、logout)。
测试场景
有了这个存根后,你可以轻松测试:
- 已登录用户 vs. 未登录用户。
- 不同角色或个人资料数据的用户。
- 身份验证错误(例如令牌获取失败)。
进一步资源
- 包含此流程的完整示例 React 应用:twd-auth0-pkce
- 带后端会话的身份验证流程示例:twd-auth0
- 官方 TWD 文档:twd.dev
扩展此方法
该模式并不限于 Auth0。任何需要在 TWD 浏览器测试中被控制的模块,都可以导出为可变对象并使用 Sinon 进行存根,从而在保持测试专注于应用行为的同时,完全掌控外部依赖。