J. Lev
J. Lev

Reputation: 317

Test if function of object has been called inside another function in jest

My code looks somewhat like this :

Class A :{
    Object foo = new foo;
    function (){
        ...
        let var = this.foo.bar()
        ...
}

And I would like to test with jest that foo.bar() has been called. I've tried with

barSpy = jest.spyOn(function, 'foo.bar');

but it doesn't work, can someone guide me toward the good syntax ?

Upvotes: 0

Views: 1121

Answers (1)

Eric Gibby
Eric Gibby

Reputation: 231

The parameters for jest.spyOn are the object that contains the function you want to spy on, and the name of the function to spy on (see: https://jestjs.io/docs/en/jest-object.html#jestspyonobject-methodname). It's a little hard to say with the given syntax above, but if foo is available as a property on an instance of A (for this example let's say your instance is called a), then a.foo is the object, and 'bar' is the name of the function.

Here's some code to better illustrate:

class A {
    constructor() {
        this.foo = new foo();
    }

    function myFunction() {
        ...
        this.foo.bar();
        ....
    }
}

...

let a = new A();
let barSpy = jest.spyOn(a.foo, 'bar');

Upvotes: 2

Related Questions