javascriptangulartypescriptunit-testingangular-unit-test

Calling function to clear localstorage value from unit test - angular


I want to test the if the localStorage is cleared down whenever I call my function.

Component

ngOnInit() {
    // Logout on reaching login screen so we can login
    this.authService.logout();
  }

authService

logout() {
    // remove logged in user from localStorage
    localStorage.removeItem('currentUser');
  }

TEST

fit('ngOnInit should logout user stored in localStorage', () => {
    // Exmample data stored as token
    localStorage.setItem('token', 'someUserToken');

    component.ngOnInit();

    expect(localStorage.getItem('token')).toEqual('{}');
});

Is there any way I can achieve this?


Solution

  • Unit testing should only concern the feature you're testing.

    This means that you should not check if the local storage is cleared : that's not what your component does. Your component calls your auth service, which then clears the storage.

    This means you should test if the correct method is called.

    it('ngOnInit should call auth.logout', () => {
        spyOn(component['authService'], 'logout');
    
        component.ngOnInit();
    
        expect(component['authService'].logout).toHaveBeenCalled();
    });