【问题标题】:How to mock multiple functions of a typescript class?如何模拟打字稿类的多个功能?
【发布时间】:2018-07-21 19:35:54
【问题描述】:

假设,我有一个打字稿类

a.ts

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

    private __functionA(){
        this.__functionB()
    }

    private __functionB(){
    }

}

现在,我的 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()

    })
})

测试因错误而失败

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

现在,当我仅模拟 ClassA__functionA 并仅针对该 函数(即 expect (instance.__functionA).toHaveBeenCalled())运行我的断言时,我的测试通过了。为什么会这样?

我怎样才能模拟一个的多个函数

如果我在这里做错了什么,请纠正我。

注意:- 我正在使用 jest 来运行我的测试

【问题讨论】:

    标签: function unit-testing typescript mocking jestjs


    【解决方案1】:

    找到答案,

    我只需要更换

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

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

    一切正常。

    希望,这对某人有帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-10
      • 2019-09-24
      • 2019-04-10
      • 1970-01-01
      • 1970-01-01
      • 2022-01-24
      • 2017-12-19
      • 2019-01-09
      相关资源
      最近更新 更多