简体   繁体   English

如何模拟打字稿类的多个功能?

[英]How to mock multiple functions of a typescript class?

Suppose, I have a typescript class 假设我有一个打字稿课

a.ts a.ts

export class A {
    constructor() {
         this.__functionA()
    }

    private __functionA(){
        this.__functionB()
    }

    private __functionB(){
    }

}

Now, I have some tests for my Class 现在,我的班级有一些测试

import { A } from "./a"

describe("Class A",() => {

    it(`__functionB should Have been called`,() => {

        A.proptotype.__functionB = jest.fn()
        A.proptotype.__functionA = jest.fn()

        let instance = new A()

        expect (instance.__functionB).toHaveBeenCalled()
        expect (instance.__functionA).toHaveBeenCalled()

    })
})

the tests fail with an error 测试失败并显示错误

expect(jest.fn()).toHaveBeenCalled()

Now, when I mock only the __functionA of Class A and run my assertions against only that function , ie expect (instance.__functionA).toHaveBeenCalled() , my test pass. 现在,当我仅模拟A __functionA并仅对该函数运行我的断言时,即我的测试通过expect (instance.__functionA).toHaveBeenCalled() Why so? 为什么这样?

And How can I mock more than one functions of a Class ? 我如何模拟一个类的多个功能

Correct me, if I am doing something wrong here. 纠正我,如果我在这里做错了。

NB:- I am using jest to run my tests . 注意:- 我在开玩笑地进行测试

Found the answer, 找到了答案,

I just had to replace 我只需要更换

A.proptotype.__functionB = jest.fn()
A.proptotype.__functionA = jest.fn()

with

jest.spyOn(A.proptotype,__functionA)
jest.spyOn(A.proptotype,__functionB)

and everything works fine. 一切正常。

Hope, this helps someone. 希望这对某人有帮助。

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

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