Javascript 仅使用ngOnInit函数测试简单角度分量

Javascript 仅使用ngOnInit函数测试简单角度分量,javascript,angular,unit-testing,testing,karma-runner,Javascript,Angular,Unit Testing,Testing,Karma Runner,说到测试,我是一个初学者,我希望你能向我解释什么是好的实践 我有一个简单的服务: export class SessionService { fetchFromStorage() { let x = localStorage.getItem('email'); return JSON.parse(x); } saveInStorage(email) { localStorage.setItem('email', JSON.stringify(email)); } }

说到测试,我是一个初学者,我希望你能向我解释什么是好的实践

我有一个简单的服务:

export class SessionService {
fetchFromStorage() {
    let x = localStorage.getItem('email');
    return JSON.parse(x);
}

saveInStorage(email) {
    localStorage.setItem('email', JSON.stringify(email));
}
}
以及使用该服务的组件:

export class LoginComponent implements OnInit, OnChanges {
email;

constructor(private service: SessionService) {
}

ngOnInit() {
    this.email = this.service.fetchFromStorage();
}

save() {
    this.service.saveInStorage(this.email);
}
}
我知道我应该创建localStorageMock?例如,在调用saveInStorage()之后,我必须检查localStorageMock是否包含我传递给该函数的参数? 我不确定如何测试fetchFromStorage,我是否应该在localStorageMock中创建以下内容:

export class {
getItem(x){
if(x = 'email') return 'sth';
}
}

第三个问题,我的组件中的ngOnInit呢?编写测试不是很简单吗?

我认为,如果您的组件能够成功地从本地存储中获取数据,然后从本地存储中获取数据,那么测试是值得的。我将使用该库使测试角度组件更容易一些

我的组件具有以下模板:

<button class="update-button" (click)="save()"> </button>
<input class="email-input" [(ngModel)]="email" />
我只为本地存储创建了间谍。如果您将在localStorage上进行更多测试,那么最好将其提取到某个类中,然后您可以将其作为依赖项添加到测试中

import {AppComponent} from "./app.component";
import {AppModule} from "./app.module";
import test, {App, click, expectThat, type} from "ng-test-runner";

describe('Local storage Component', () => {

  let app: App;
  let store = {};

  beforeAll(() => {
    spyOn(localStorage, 'getItem').and.callFake(function (key) {
      return store[key];
    });
    spyOn(localStorage, 'setItem').and.callFake(function (key, value) {
      return store[key] = value + '';
    });
    spyOn(localStorage, 'clear').and.callFake(function () {
      store = {};
    });
  });

  beforeEach(() => {
    app = test(AppModule);
  });

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

  it('fetch email from local storage', () => {
    localStorage.setItem('email', 'emailFromLocalStorage');
    const comp = app.run(AppComponent);

    comp.verify(
      expectThat.textOf('.email').isEqualTo('emailFromLocalStorage')
    );
  });

  it('update email in local storage', () => {
    localStorage.setItem('email', 'emailFromLocalStorage');
    const comp = app.run(AppComponent);

    comp.perform(
      type('newEmail@gmail.com').in('.email-input'),
      click.in('.update-button')
    );

    comp.verify(
      () => expect(localStorage.getItem('email')).toEqual('newEmail@gmail.com')
    );
  });
});