2

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. 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()

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? All that this method does is calling loadData. But how to check that if get property returns true the method is calling? I'm confused ((

1 Answer 1

2

In this case you mock the this.loadData() function using spyOn method of jasmine. As assertion you expect the this.loadData() method to have been called (or not have been called based on the value of this.isLogged).

To expect a function call jasmine has for the spies the toHaveBeenCalled() function. Some example can be found 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.

The logic of this.loadDate() is tested separately so it is not needed to test that from the ngOnInit().

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.