添加了相关测试文件,引入Tailwindcss
Change-Id: I12054143571bb688590af0357125a0ed26ff2050
diff --git a/src/contexts/AuthContext.test.jsx b/src/contexts/AuthContext.test.jsx
new file mode 100644
index 0000000..9536be2
--- /dev/null
+++ b/src/contexts/AuthContext.test.jsx
@@ -0,0 +1,48 @@
+import { describe, it, expect, beforeEach } from 'vitest';
+import { render, screen } from '@testing-library/react';
+import { AuthProvider, useAuth } from './AuthContext';
+
+// 创建一个测试组件来使用 useAuth hook
+const TestComponent = () => {
+ const { user, hasRole } = useAuth();
+ return (
+ <div>
+ <div data-testid="user-info">{user ? JSON.stringify(user) : 'no user'}</div>
+ <div data-testid="is-admin">{hasRole('admin') ? 'is admin' : 'not admin'}</div>
+ </div>
+ );
+};
+
+describe('AuthContext', () => {
+ beforeEach(() => {
+ window.localStorage.clear();
+ });
+
+ it('应该提供默认值', () => {
+ render(
+ <AuthProvider>
+ <TestComponent />
+ </AuthProvider>
+ );
+
+ expect(screen.getByTestId('user-info')).toHaveTextContent('no user');
+ expect(screen.getByTestId('is-admin')).toHaveTextContent('not admin');
+ });
+
+ it('应该从 localStorage 加载用户信息', () => {
+ // 模拟管理员
+ window.localStorage.setItem('user', JSON.stringify({
+ username: 'admin',
+ role: 'admin'
+ }));
+
+ render(
+ <AuthProvider>
+ <TestComponent />
+ </AuthProvider>
+ );
+
+ expect(screen.getByTestId('user-info')).toHaveTextContent('admin');
+ expect(screen.getByTestId('is-admin')).toHaveTextContent('is admin');
+ });
+});
\ No newline at end of file