在我的 React 应用程序中使用 Zustand 等库来实现测试设置很困难。 ReferenceError:本地存储未定义

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

我正在尝试为我的 React 应用程序实现一组测试。因此,我要做的第一件事就是实现一些模拟,例如身份验证、localStorage 等。我创建了一个 localStorageMock 来在测试应用程序时为其保存 JSON webtoken,但由于某种原因,我使用了 zustand 存储要获取令牌,找不到我的 localStorageMock。它一直说 ReferenceError: localStorage is not Defined。通过我的测试设置,我总是在每次测试之前启动 localStorageMock。

1° - useAuthStore:

export const useAuthStore = create<AuthenticationsStore>((set) => ({
    authentication: {
        token: localStorage.getItem('token') || ('' as string),
        permissions: [],
        originalGroupId: 0,
    },
    setAuthentication: (authentication) =>
        set(() => ({
            authentication: authentication,
        })),
    setPermissions: (permissions: string[]) =>
        set((state) => ({
            authentication: {
                ...state.authentication,
                permissions: permissions,
            },
        })),
    setToken: (token: string) =>
        set((state) => {
            localStorage.setItem('token', token);
            return {
                authentication: {
                    ...state.authentication,
                    token: token,
                },
            };
        }),
    setOriginalGroupId: (originalGroupId: number) =>
        set((state) => ({
            authentication: {
                ...state.authentication,
                originalGroupId: originalGroupId,
            },
        })),
    dismissAuthentication: () =>
        set(() => {
            localStorage.removeItem('token');
            return {
                authentication: {
                    token: '',
                    permissions: [],
                    originalGroupId: 0,
                },
            };
        }),
}));

2° - LocalStorageMock

export class LocalStorageMock implements Storage {
    private store: Record<string, string>;

    constructor() {
        this.store = {};
    }

    getItem(key: string): string | null {
        return this.store[key] || null;
    }

    setItem(key: string, value: string): void {
        this.store[key] = value.toString();
    }

    removeItem(key: string): void {
        delete this.store[key];
    }

    clear(): void {
        this.store = {};
    }

    // Implementação das propriedades da interface Storage
    // Adapte conforme necessário
    get length(): number {
        return Object.keys(this.store).length;
    }

    key(index: number): string | null {
        const keys = Object.keys(this.store);
        return index >= 0 && index < keys.length ? keys[index] : null;
    }
}

global.localStorage = new LocalStorageMock();

3° - 我的测试实施。

import { render, fireEvent, screen } from '@testing-library/react';
import PaginaInicial from '../../../features/inicial/routes/PaginaInicial';
import { accessToken } from '../../utils/globalMocks/access-token-json.mock.';
import { LocalStorageMock } from '../../utils/globalMocks/localStorage.mock';
import 'mock-local-storage';

describe('Página Inicial', () => {
    beforeEach(() => {
        if (!global.localStorage) {
            global.localStorage = new LocalStorageMock();
        }
        global.localStorage.setItem(
            'token',
            accessToken.token_type + ' ' + accessToken.access_token,
        );
    });

    afterEach(() => {
        global.localStorage.clear();
    });

    test('Renderização componentes página inicial', async () => {
        render(<PaginaInicial />);
        // Restante do seu código de teste
    });
});

4° - 错误

我尝试在网络、zustand lib 和 chatGPT 上找到解决方案。但我找不到这个问题的解决方案。我期望当我在全球范围内创建 localstorage 时它会像往常一样工作,但由于某些原因,库中有些东西我真的不知道如何使其工作。

reactjs testing mocking local-storage zustand
1个回答
0
投票

我在用 jest 编写时也遇到过访问测试用例上的本地存储。

通过在我的

index.test.tsx

中添加以下块来解决它
// imports

Object.defineProperty(window, 'localStorage', {
  value: new MockLocalStorage()
})

describe(()=> {
   test(()=>{})
   test(()=>{})
})

不要将其添加到全局中,而是将其放入窗口中,很想知道更好的答案(如果有)!

© www.soinside.com 2019 - 2024. All rights reserved.