using Jasmines spyon upon a private method

jasmine test private methods
jasmine spy on class method
how to mock private methods in xunit
phpunit mock private method
should we mock private methods
spyon method does not exist
jasmine spyon multiple methods
jasmine spy on object

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();
    });
});

Just add a generic parameter < any> to the spyon() function:

 spyOn<any>(fakePerson, 'sayHello');

It works on perfectly !

How to Spy on a Private Method with a Jasmine, I was testing a public method, but that public method called a private method which returned some an Observable. I wanted to spy on the method,  Jasmine provides the spyOn () function for such purposes. spyOn () takes two parameters: the first parameter is the name of the object and the second parameter is the name of the method to be spied upon. It replaces the spied method with a stub, and does not actually execute the real method.

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();
    });
});

Unable to use jasmine.spyOn on private/protected functions · Issue , Is spyOn usage on private methods recommended? You could have used a cast (​"as any") in the extreme cases when you badly need that, but  If your method is being called by another method, you may want it to return something. You can tell Jasmine what to return using the andReturn(value) method: testPerson.getName = jasmine.createSpy("getName() spy").andReturn("Bobby"); And finally, here's a way to substitute an entirely different method body for the original:

🤳 🧔 using Jasmines spyon by private method, Using Jasmines spyon in a private method Is it possible to use the Jasmine unit testing platform Spyon method on private class methods? The docu Jasmine's spyOn is good to change a method's behavior, but is there any way to change a value property (rather than a method) for an object? the code could be like below: spyOn(myObj, 'valueA').

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

Angular Testing: Mock Private Functions - David Dal Busco, Angular Testing: Mock Private Functions. How to mock a private function in your automated Angular tests with Jasmine or Jest. Since jasmine v2.5, use the global allowRespy() setting. jasmine.getEnv().allowRespy(true); You'll be able to call spyOn() multiple times, when you don't want and/or have access to the first spy.

In my case (Typescript):

jest.spyOn<any, string>(authService, 'isTokenActual')

OR with mocked result:

jest.spyOn<any, string>(authService, 'isTokenActual').mockImplementation(() => {
  return false;
});

Angular Testing: Mock Private Functions - DEV, How to mock a private function in your automated Angular tests with Jasmine or Jest. Tagged with angular, testing, javascript, webdev. Teams Private questions and answers for your actually you just need to use the spyOn method like spyOn since i am using jasmine 2.0 – Malik Jun 8 '15 at 7

How to avoid the need to Unit test private methods, So - don't mock your private methods. Use them to understand what you need to test in order to provide good coverage of the functionality that  I've had some problems using spyOn(window, 'test') using chutzpah for running the tests as part of our automation due to 'window' not being assigned. Using jasmine.createSpy() got around this. – Henners Sep 24 '13 at 13:43

Spy on JavaScript Methods Using the Jasmine Testing Framework, How many parameters the function was called with. Advertisement. In Jasmine, mocks are referred to as spies. There are two ways to create a spy  I have a function I'd like to test which calls an external API method twice, using different parameters. I'd like to mock this external API out with a Jasmine spy, and return different things based on the parameters. Is there any way to do this in Jasmine? The best I can come up with is a hack using andCallFake:

How to spyOn a Service method called in the Service constructor, How to spy on a service method that is called inside the same service constructor using Karma/Jasmine for unit testing. 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.

Comments
  • I tried this solution and it works perfectly well. Additionally, a private field can be accessed using array index notation, like I mentioned earlier on.
  • Neither of those worked for me. You can't access via array notation since the spyOn takes two arguments. Putting <any> as shown also throws an error of the wrong number of arguments. This is what worked for me: spyOn(fakePerson as any, 'sayHello');
  • I do this as well. Is there a better way without being so 'generic' using any? I tried for example spyOn<fakePerson>(fakePerson, 'sayHello'); But then still complains about 'say hello'. IS it possible something like spyOn<fakePerson><fuction> or something? For a bit better context?
  • Can someone also explain why this solution works? What exactly does adding <any> do so that this works?
  • @risingTide Adding <any> drops the type checking, so there'll be no TypeScript compile-time errors (and no errors in your editor). But the TypeSciprt ultimately gets compiled into Javascript where every method is public, so this will work to drop the Typescript errors.
  • I get a type error if I try to call a non-exported (private) function: Error:(33, 56) TS2345:Argument of type '"sayHello"' is not assignable to parameter of type '"sayGoodbye"'. where sayGoodbye is a public method on Person and sayGoodbye is private. I have to cast it to any ("sayHello" as any)
  • I need more context here, it seems like your assignment is not working and not the access to the private function. But try to access it like this: person["sayHello"] instead of person.sayHello (if that's what you are doing). This is not best practice, but in rare cases is forgiven ;)
  • Agreed with @FlavorScape. Typescript (at least 1.7 and up) expects the spied-on finction to be public, and since sayHello is not type sayGoodbye (or any of the other public functions) it will throw an error. I've only been able to fix this using the spy<any> listed above.
  • It seems like things have changed since my last comment. spy<any> may indeed be the right answer. Thanks
  • Down voted because you didn't address the main concern which is how do you spy on a private method. This code is not all that different than what was originally provided in the question.
  • @JeffryHouser The sayHello is the a private method. and the first line is how to create a spy on it. The second line is the test.