'Angular/Jasmine service method was not called
I am trying to do simple test when user click on button it should call method from service. But I am still getting just that method is not called. Component.ts
@Component({
...
providers: [MyService]
})
export class MyComponent implements OnInit, OnDestroy {
constructor(public myService: myService) { }
}
Component.html
<button id="myId"
(click)="myService.myMethodX()">
</button>
MyService.ts
@Injectable()
export class MyService {
constructor() { }
myMethodX(){
...
}
}
And in jasmine I am testing it like this.
const mySpyObj = jasmine.createSpyObj('MyService', ['myMethodX']);
it('...', () => {
// Given
const button = ...
// When
button.click();
fixture.detectChanges();
// Then
expect(mySpyObj.myMethodX).toHaveBeenCalled();
});
but it says that its not called what I am doing wrong?
Solution 1:[1]
Method called myMethodX from your component is not a method of the service. Inside of that method service method is called (I assume), for example myService.calculate().
What you should spy on and test is that method from service. You can do something like this:
// Arange
spyOn(myService, 'calculate');
// Act
button.click();
// Assert
expect(myService.calculate).toHaveBeenCalled();
Second approach would be to test if method of a component is called:
// Arange
spyOn(component, 'myMethodX');
// Act
button.click();
// Assert
expect(component.myMethodX).toHaveBeenCalled();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Chaka15 |
