簡體   English   中英

測試 object 的 function 是否已在另一個 function 中被調用

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

我的代碼看起來有點像這樣:

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

我想開玩笑地測試一下 foo.bar() 已經被調用了。 我試過了

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

但它不起作用,有人可以指導我使用好的語法嗎?

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 -方法名)。 上面給定的語法有點難說,但如果foo可作為A實例的屬性使用(對於本例,假設您的實例稱為a ),那么a.foo是 object 和'bar'是 function 的名稱。

這里有一些代碼可以更好地說明:

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