如何用sinon存根打字的一个类的私有方法
我正在编写一个公共方法的unit testing,然后调用typecript(Node JS)中写入的类的私有方法。
示例代码
class A { constructor() { } public method1() { if(this.method2()) { // Do something } else { // Do something else } } private method2() { return true; } }
现在来testingmethod1()我需要存根method2()这是一个私有方法。
这里我正在尝试:
sinon.stub(A.prototype, "method2");
Typescript正在抛出错误:
Argument of type '"method2"' is not assignable to parameter of type '"method1"'
任何帮助,将不胜感激。 谢谢
问题在于sion
的定义使用了这个stub
函数的定义:
interface SinonStubStatic { <T>(obj: T, method: keyof T): SinonStub; }
这意味着第二个参数必须是T
types的成员(公共名称)的名称。 这可能是一个很好的限制,但在这种情况下,这是有点太限制。
你可以通过投射到any
:
sinon.stub(A.prototype, <any>"method2");