TWD Tip: Auth0 훅 스텁 및 React 모듈 목업
Source: Dev.to
배경
인증은 현대 애플리케이션에서 가장 까다로운 기능 중 하나입니다.
Auth0와 같은 도구는 특히 React와 함께 useAuth0 같은 훅을 제공하여 인증 관리를 크게 도와줍니다.
이 훅들을 테스트하는 것은 어려울 수 있습니다:
- Cypress는 교차 도메인 테스트를 위해 별도 설정이 필요합니다.
- Vitest는 데이터 모킹이 필요하지만, 테스트 결과는 터미널에 단순히 통과/실패만 표시합니다.
- 실제 사용자를 생성하고 검증해야 합니다.
Testing While Developing (TWD)은 인프라가 아니라 동작을 테스트하도록 권장합니다. 인증 제공자를 직접 테스트할 필요는 없으며, 앱이 의존하는 인증 동작만 시뮬레이션하면 됩니다.
Auth0 훅 스텁하기
PKCE 흐름을 사용하는 Auth0와 React 앱에서는 단순한 요청보다 useAuth0 훅에 의존합니다. 다음 패턴을 사용하면 테스트에서 인증을 완전히 제어할 수 있습니다.
래퍼 모듈
// src/hooks/useAuth.ts
import { useAuth0 } from "@auth0/auth0-react";
const useAuth = () => useAuth0();
export default { useAuth };
왜 객체를 내보내나요?
ESModules는 기본적으로 불변입니다. 이름이 있는 내보내기(export const useAuth = …)는 런타임에 모킹할 수 없지만, 객체 속성은 가능합니다. 객체를 가변적으로 내보내면 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). - 모의 사용자 데이터 제공 (
userMock). - 토큰 조회 스텁 (
getAccessTokenSilently). - 로그인/로그아웃 흐름 모킹 (
loginWithRedirect,logout).
테스트 시나리오
스텁을 설정해두면 다음과 같은 상황을 손쉽게 테스트할 수 있습니다:
- 로그인 상태와 로그아웃 상태.
- 서로 다른 역할이나 프로필 데이터를 가진 사용자.
- 인증 오류(예: 토큰 가져오기 실패).
추가 자료
- 이 흐름을 적용한 전체 예시 React 앱: twd-auth0-pkce
- 백엔드 세션과 연동된 인증 흐름 예시: twd-auth0
- 공식 TWD 문서: twd.dev
접근 방식 확장하기
이 패턴은 Auth0에만 국한되지 않습니다. TWD 브라우저 테스트에서 제어가 필요한 모든 모듈을 가변 객체로 내보내고 Sinon으로 스텁하면, 외부 의존성을 완전히 제어하면서도 테스트는 애플리케이션 동작에 집중할 수 있습니다.