如何使用sinon存储用typescript编写的类的私有方法

问题描述 投票:8回答:1

我正在为一个公共方法编写单元测试,而这个方法又调用了用typescript(Node JS)编写的类的私有方法。

示例代码

class A {
   constructor() {  
   }
   public method1() {  
       if(this.method2()) {
          // Do something
       } else {
          // Do something else
       }
   }
   private method2() {
      return true;
   }
}

现在测试method1()我需要stub方法2()这是一个私有方法。

在这里我正在尝试:

sinon.stub(A.prototype, "method2");

Typescript抛出错误:

Argument of type '"method2"' is not assignable to parameter of type '"method1"'

任何帮助,将不胜感激。谢谢

node.js unit-testing typescript sinon
1个回答
10
投票

问题是sinon的定义对stub函数使用以下定义:

interface SinonStubStatic { <T>(obj: T, method: keyof T): SinonStub; }

这意味着第二个参数必须是T类型的成员(公共成员)的名称。这通常是一个很好的限制,但在这种情况下,它有点过于严格。

您可以通过投射到any来解决它:

sinon.stub(A.prototype, <any>"method2");
© www.soinside.com 2019 - 2024. All rights reserved.