Mohammed Shirhaan
Mohammed Shirhaan

Reputation: 553

How to check if a method from a service is called or not in Jasmine unit testing without using spyOn in Angular?

I have a method say performAnalytics() in a service say analyticsService that is called when you click on a specific element in the HTML. I am writing unit test cases and trying to cover the code using jasmine. I trigger the click event on the HTML element testElement.dispatchEvent(new Event('click'));. The performAnalytics() gets called the code coverage is successful. The performAnalytics method forms an object and inturn calls another method from some other service.

Now I want to write an expectation as follows

expect(analyticsService.performAnalytics()).toHaveBeenCalled()

For this to work I need to use spyOn on the method as follows

spyOn<any>(analyticsService, 'performAnalytics');

But if I use spyOn, the method performAnalytics will be mocked and will not be executed in real. Hence the code coverage of the method performAnalytics() is not successful.

Please help. I am new to Angular. Any other alternative to spyOn to use toHaveBeenCalled() ?

If I don't write the expectation, and simply trigger the click event to cover the code it will show warning as 'SPEC HAS NO EXPECTATIONS'

Upvotes: 1

Views: 1982

Answers (1)

vadimk7
vadimk7

Reputation: 8303

Leave your expect as is and use callThrough to spy and delegate calls to actual implementation:

spyOn<any>(analyticsService, 'performAnalytics').and.callThrough();

Upvotes: 3

Related Questions