【发布时间】:2020-02-10 14:15:01
【问题描述】:
我有一堂课:
export default class A {
data: string
constructor(data?: any) {
if (data !== undefined) {
this.data = data.stingValue
}
}
}
然后我有另一个类在公共方法中使用A 构造函数:
export default class B {
public doSomething(data: any) {
const a = new A(data)
dependecy.doAnotherThing(a)
}
}
并测试:
it(('shoud doSomething') => {
const doAnotherThingStub = stub(B.prototype, 'doAnotherThing')
//this part does not work, just an example of what I would like to achieve
const doAnotherThingStub = stub(A.prototype, 'constructor').returns({dataReturendFromAConstructorStub: true})
// end of this part
const b = new B()
b.doSomething({})
expect(doAnotherThingStub.calledWith({dataReturendFromAConstructorStub: true})).to.be.true
})
我的目标是存根类 A 构造函数。我对 A 类有单独的测试,我不想再次测试它。我需要像stub(A.prototype,'constructor') 这样的东西。我曾尝试使用proxyquire 和存根,但我无法注入假构造函数,要么调用真正的构造函数,要么得到类似:A_1.default is not a constructor。以前我有一些情况,我需要存根一个我在测试用例中直接调用的类或存根该类的一个方法,这些都非常简单。但我正在为这个案子而苦苦挣扎。
模拟A 的正确方法是什么?
【问题讨论】:
标签: typescript unit-testing sinon