1

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?

johannesMatevosyan
  • 1,974
  • 2
  • 30
  • 40
physicsboy
  • 5,656
  • 17
  • 70
  • 119

1 Answers1

0

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();
});
  • Could I not incorporate both things into the one test? ie have `localStorage.setItem('token','blah');` and then expect it to be cleared below? in practise, I have tried this, and it does not clear the localStorage... – physicsboy Jul 26 '18 at 10:51
  • You can, but it's not best practice (and probably not even unit testing) –  Jul 26 '18 at 10:52
  • Still the same answer : per definition, a *unit test* tests an *unit* : if you test that your service does something, you're testnig *two units*. –  Jul 26 '18 at 10:55
  • 1
    Ok I understand what you mean properly now. This unit is just to call the authService.logout, the test I am trying to incorporate into the one you showed should be used within the authService.spec to test the logout function itself! Thanks :-) Also... I'd been looking for how to spy on things like this! Lifesaver – physicsboy Jul 26 '18 at 10:58
  • Exactly ! and no problem, consider [reading the doc](https://jasmine.github.io/api/3.0/global) to find everything you can do with Jasmine ! –  Jul 26 '18 at 10:58