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
No cause you cant access a private function outside the context of your instance.
Btw, its not a good idea to spy on objects you wanna test. When you test if a specific method in your class you want to test is called, it says nothing. Lets say you wrote the test and it passed, two weeks later you refactor some stuff in the function and add a bug. So your test is still green cause you the function called. B
Spies are useful when you work with Dependency Injection, where all external dependencies are passed by the constructor and not created in your class. So lets say you have a class that needs a dom element. Normaly you would use a jquery selector in the class to get this element. But how you wanna test that something is done with that element? Sure you can add it to your tests pages html. But you can also call your class passing the element in the constructor. Doing so, you can use spy to check if your class interacts with that element as you expected.
If you want to test private functions within a class, why not add a constructor to your class that signals that those private functions get returned?
Have a read through this to see what I mean: http://iainjmitchell.com/blog/?p=255
I have been using a similar idea and so far its working out great!
const spy = spyOn<any>(component, 'privateMethod');
expect(spy).toHaveBeenCalled();
To avoid lint warnings regarding object access via string literals, create a local constant of the spy object.
Typescript gets compiled to javascript and in javascript every method is public. So you can use array index notation to access private methods or fileds, viz:
Object['private_field']
if you use Typescript for your objects, the function isn't really private.
All you need is to save the value that returned from spyOn
call and then query it's calls
property.
At the end this code should work fine for you (at least it worked for me):
describe("Person", function() {
it("calls the sayHello() function", function() {
var fakePerson = new Person();
// save the return value:
var spiedFunction = spyOn<any>(fakePerson, "sayHello");
fakePerson.helloSomeone("world");
// query the calls property:
expect(spiedFunction.calls.any()).toBeFalsy();
});
});
In my case (Typescript):
jest.spyOn<any, string>(authService, 'isTokenActual')
OR with mocked result:
jest.spyOn<any, string>(authService, 'isTokenActual').mockImplementation(() => {
return false;
});