127

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

13 Answers 13

219

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

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

It works on perfectly !

5
  • 3
    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. Commented May 23, 2018 at 22:04
  • 14
    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');
    – Russ
    Commented Jun 15, 2018 at 18:58
  • 3
    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?
    – L1ghtk3ira
    Commented Nov 23, 2018 at 18:59
  • 4
    Can someone also explain why this solution works? What exactly does adding <any> do so that this works?
    – risingTide
    Commented Mar 7, 2019 at 18:03
  • 15
    @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.
    – WindUpDurb
    Commented Mar 20, 2019 at 17:51
45
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

1
  • 1
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.
    – Igor F.
    Commented Feb 19, 2020 at 13:41
19

Let say sayHello(text: string) is a private method. You can use the following code:

// Create a spy on it using "any"
spyOn<any>(fakePerson, 'sayHello').and.callThrough();

// To access the private (or protected) method use [ ] operator:
expect(fakeperson['sayHello']).toHaveBeenCalledWith('your-params-to-sayhello');
  • Create a spy on private method using any.
  • To access the private (or protected) method use [] operator.
3
  • 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. Commented Oct 18, 2019 at 19:13
  • @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. Commented Oct 18, 2019 at 19:50
  • Got it; your answer is missing the explanation of how to spy on a private method--AKA using the <any> tag. That is why I got confused. Commented Oct 19, 2019 at 20:06
10

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();
    });
});
7
  • 4
    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) Commented May 9, 2017 at 17:40
  • 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 ;)
    – jurl
    Commented May 10, 2017 at 19:09
  • 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.
    – Beartums
    Commented May 10, 2018 at 5:38
  • 1
    It seems like things have changed since my last comment. spy<any> may indeed be the right answer. Thanks
    – jurl
    Commented May 10, 2018 at 9:56
  • spy<any> is a revelation. Commented Feb 12, 2021 at 12:02
9
spyOn(fakePerson, <never>'sayHello');
spyOn(fakePerson, <keyof Person>'sayHello');

Both silence the type error and don't interfere with TSLint's no-any rule.

5
  • Does not compile with react, so better use the as type cast instead. Commented Apr 21, 2022 at 8:18
  • spyOn(fakePerson, <keyof as any>'sayHello');
    – Leo Lanese
    Commented Sep 6, 2022 at 11:30
  • I cannot understand how could one consider using Typescript and still use any as a type...
    – Niko
    Commented Sep 26 at 10:23
  • The dos and don'ts of TS regarding any
    – Niko
    Commented Sep 27 at 9:14
  • any in test code is bearable (I would allow it) but there are better alternatives which do not require disabling of no-any in TSLint.
    – mlntdrv
    Commented Sep 30 at 7:51
4

In my case (Typescript):

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

OR with mocked result:

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

There is an update to the context of this question, in regard to what "private" means. As of ES2022, JavaScript has private class fields, that are prefixed with a hash (#). These properties are truly private, and even with the solutions suggested, cannot be spyOn()ed.

2
fakePerson['sayHello'] = jasmine.createSpy().and.callThrough();
expect(fakePerson['sayHello']).toHaveBeenCalled();
2
  • 5
    Please, add some explanations. Commented Jan 30, 2023 at 19:46
  • This is the only type-sane solution if you're using Typescript.
    – Niko
    Commented Sep 26 at 10:25
1

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']
2
  • The blog link is dead unfortunately. Commented Sep 16, 2019 at 7:10
  • 1
    Down voted here, part for the dead blog link; part for the fact that we cannot use object array notation to set up a spy. Commented Oct 18, 2019 at 19:16
0

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!

2
  • 5
    If you publish your privat method it's not privat anymore. Btw, as I described in my answer it make not much sense to test privat method. Commented Dec 13, 2011 at 11:10
  • 1
    We can agree is disagree on that. Our javascript codebase is massive and we only expose a handleful of public functions/properties on some of our classes. A lot of logic is handled in those private functions. I only public a private method so the testing framework has access to it. If the constructor is not called correctly then the private function is not returned.
    – StevenMcD
    Commented Dec 13, 2011 at 11:36
0

When your class looks like this

class SomeClass {
    private method(){}
}

In test you can do

// @ts-ignore
class SomeClassForTest extends SomeClass {
    public method(){}
}

let service: SomeClassForTest = TestBed.inject(SomeClass) as any;

IMHO it is better than using , because you dont have to do it on each line.

-2

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.

4
  • 31
    It's not correct to say 'its not a good idea to spy on objects you wanna test`. Use of spies is not limited to checking whether not a function was simply called and that's it. You can use spies to check returned values, to replace functions entirely for test cases, throwing errors, etc. I would suggest reading the jasmine documentation for a more complete understanding. Commented Sep 23, 2015 at 18:13
  • 2
    its not a good idea to spy !?? you cant be more wrong! yeap i agree with Tim and you should look at the doco, whos voted this up?!
    – AltF4_
    Commented Feb 21, 2017 at 11:21
  • 3
    Thats not what I said. Its ok to use spies. But you should handle the object you wanna test as a black box. Only test what goes in and out. Don't test internals of the black box, what you would do if you spy on methods of the object under test. So spy on on callbacks that you pass into the object is totally fine. Commented Feb 21, 2017 at 11:34
  • It's exactly the opposite. You are testing "unit", you are not interested what other "unit" is doing. You will have test for other "unit". Commented Jun 17, 2021 at 19:57
-4
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.