简体   繁体   中英

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'

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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