简体   繁体   English

测试 object 的 function 是否已在另一个 function 中被调用

[英]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.我想开玩笑地测试一下 foo.bar() 已经被调用了。 I've tried with我试过了

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

but it doesn't work, can someone guide me toward the good syntax?但它不起作用,有人可以指导我使用好的语法吗?

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 ). 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 -方法名)。 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.上面给定的语法有点难说,但如果foo可作为A实例的属性使用(对于本例,假设您的实例称为a ),那么a.foo是 object 和'bar'是 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');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM