is it possible to use Jasmine unit testing framework's spyon method upon a classes private methods?
The documentation gives this example but can this be flexivble for a private function?
describe("Person", function() { it("calls the sayHello() function", function() { var fakePerson = new Person(); spyOn(fakePerson, "sayHello"); fakePerson.helloSomeone("world"); expect(fakePerson.sayHello).toHaveBeenCalled(); }); });
SpyOn is a Jasmine feature that allows dynamically intercepting the calls to a function and change its result.
To test private methods, you just need to test the public methods that call them. Call your public method and make assertions about the result or the state of the object. If the tests pass, you know your private methods are working correctly.
Jasmine: createSpy() and createSpyObj() Jasmine's createSpy() method is useful when you do not have any function to spy upon or when the call to the original function would inflict a lag in time (especially if it involves HTTP requests) or has other dependencies which may not be available in the current context.
javascript - Jest spyOn() calls the actual function instead of the mocked - Stack Overflow. Stack Overflow for Teams – Start collaborating and sharing organizational knowledge.
Just add a generic parameter < any> to the spyon() function:
spyOn<any>(fakePerson, 'sayHello');
It works on perfectly !
spyOn<any>(fakePerson, 'sayHello'); expect(fakePerson['sayHello']).toHaveBeenCalled();
by adding <any>
to spyOn you remove it from typescript type check. you also need to use array index notation in order to access a private method (sayHello) in the test expect
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With