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

时间:2018-01-03 14:24:35

标签: 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 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';
}
}

第三个问题是我的组件中有哪些内容?编写测试不是很简单吗?

1 个答案:

答案 0 :(得分:1)

我认为测试你的组件是否可以成功从本地存储中获取数据然后是否可以从那里获取数据是值得的。我将使用ng-test-runner库来更轻松地测试Angular组件。

我的组件有模板:

<button class="update-button" (click)="save()"> </button>
<input class="email-input" [(ngModel)]="email" />

和测试:

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')
    );
  });
});

我只创建了localStorage的间谍。如果你对localStorage有更多的测试,可能最好将它提取到某个类 - 然后你可以将它作为一个依赖项添加到你的测试中。