jeudi 19 mars 2020

AfterAll Uncaught TypeError: localStorage.removeItem is not a function thrown

I am new to Angular testing , so i have tested small events and function but now working with fake localStorage while testing i am facing this issue localStorage.removeitem in every component . I have googled this issue but could't get the best possible solution . Can anyone help to overcome this problem .

This is how i mock the local storage for testing .

let store = {''}; // i have localData here

    const mockLocalStorage = {
        getItem: (key: string): string => {
        return key in store ? store[key] : null;
        },
        setItem: (key: string, value: string) => {
        store[key] = `${value}`;
        },
        removeItem: (key: string) => {
        delete store[key];
        },
        clear: () => {
            this.store = {};
        }
    };

    spyOn(localStorage, 'getItem')
        .and.callFake(mockLocalStorage.getItem);
    spyOn(localStorage, 'setItem')
        .and.callFake(mockLocalStorage.setItem);
    // spyOn(localStorage, 'removeItem')
    //     .and.callFake(mockLocalStorage.removeItem);
    spyOn(localStorage, 'clear')
        .and.callFake(mockLocalStorage.clear);

Aucun commentaire:

Enregistrer un commentaire