简体   繁体   English

Angular 单元测试 NgOnInit

[英]Angular Unit Testing NgOnInit

I will be very grateful if you help me to understand something.如果您能帮助我理解某些事情,我将不胜感激。 I have a component, which display some data.我有一个组件,它显示一些数据。 In ngOnInit() the http-service method is called to get data from server.在 ngOnInit() 中调用 http-service 方法从服务器获取数据。 Here is code:这是代码:

// isLogged - is get property
ngOnInit() {
  if (this.isLogged) {
    this.loadData();
 };
}

// Can't call in ngOnInit because this method is being used in other functions
loadData() {
  this.http.getData()
           .subscribe((result) => this.dataToDisplay = result);
}

get isLogged() {
    // this function checks for token in localStorage via custom token service. 
}

I write the test for loadData()我为 loadData() 编写测试

it('should load data', async(() => {
   component.loadData();
   fixture.whenStable().then( () => {
       fixture.detectChanges();
       expect(component.dataToDisplay).toEqual(mockData);
   });
});

And it works as expected.它按预期工作。 But my question is: how I should test the ngOnInit?但我的问题是:我应该如何测试 ngOnInit? All that this method does is calling loadData.这个方法所做的只是调用 loadData。 But how to check that if get property returns true the method is calling?但是如何检查 get 属性是否返回 true 方法正在调用? I'm confused ((我很困惑 ((

In this case you mock the this.loadData() function using spyOn method of jasmine.在这种情况下,您使用 jasmine 的spyOn方法模拟this.loadData() function。 As assertion you expect the this.loadData() method to have been called (or not have been called based on the value of this.isLogged ).作为断言,您希望this.loadData()方法已被调用(或未根据this.isLogged的值调用)。

To expect a function call jasmine has for the spies the toHaveBeenCalled() function.期望 function 调用 jasmine 对间谍有toHaveBeenCalled() function。 Some example can befound here .一些例子可以在这里找到 I assume that this.isLogged can be set directly in the tests on the fixture.componentInstance , so it can be set to the wished value for the specific test case.我假设this.isLogged可以直接在fixture.componentInstance上的测试中设置,因此可以将其设置为特定测试用例的期望值。

The logic of this.loadDate() is tested separately so it is not needed to test that from the ngOnInit() . this.loadDate()的逻辑是单独测试的,因此不需要从ngOnInit()进行测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM