Angular Testing: Mock Private Functions

How to mock a private function in your automated Angular tests with Jasmine or Jest

David Dal Busco
4 min readApr 8, 2020
Photo by Overture Creations on Unsplash

I share one trick a day until (probably not) the end of the COVID-19 quarantine in Switzerland, April 19th 2020. Eleven days left until hopefully better days.

This week I made several progress in one of my client’s project and had therefore to write new test cases. For one of these, I notably had to mock a private function using Jest.

When I was replicating this test for the purpose of this blog post, I figured out that I was actually using Jasmine as it is the default test suite used when creating new Ionic Angular applications 😁.

That’s why I am sharing today both solutions or how to mock a private function with Jasmine or Jest 😇.

Credits

This blog post Jest’s solution has been provided by Brian Adams on Stackoverflow. The Jasmine one was inspired by the answer of jurl on the same platform too.

Kudos to them, not all heroes wear capes!

Test Setup

Once again, I am using my favorite API for the demo purpose: the free DOG Api.

--

--

David Dal Busco
David Dal Busco

Written by David Dal Busco

Freelancer by day | Creator of Juno.build by night

Responses (2)