Unit testing 如何将Sinon与Typescript一起使用?
如果我将sinon与typescript一起使用,那么如何将sinon模拟投射到我的对象实例 例如,将返回SinonMock,但我的被测控制器可能需要将特定服务传递给其构造函数Unit testing 如何将Sinon与Typescript一起使用?,unit-testing,typescript,sinon,Unit Testing,Typescript,Sinon,如果我将sinon与typescript一起使用,那么如何将sinon模拟投射到我的对象实例 例如,将返回SinonMock,但我的被测控制器可能需要将特定服务传递给其构造函数 var myServiceMock: MyStuff.MyService = <MyStuff.MyService (sinon.mock(MyStuff.MyService)); controllerUnderTest = new MyStuff.MyController(myServiceMock, $log
var myServiceMock: MyStuff.MyService = <MyStuff.MyService (sinon.mock(MyStuff.MyService));
controllerUnderTest = new MyStuff.MyController(myServiceMock, $log);
var-myservicecomck:MyStuff.MyService=在将类型缩小为特定类型之前,可能需要使用
类型断言使类型变宽:
var myServiceMock: MyStuff.MyService =
<MyStuff.MyService> <any> (sinon.mock(MyStuff.MyService));
如果使用createStubInstance
方法而不是mock
,Sinon可以非常轻松地基于构造函数创建存根
使用和的示例可能如下所示:
import*作为sinon从“sinon”导入;
从“柴”进口*作为柴;
// ... 为测试中的类导入
const expect=chai.expect;
const sinonChai=要求(“sinon chai”);
柴.用(新竹);
描述('MyController',()=>{
它('使用我的服务',()=>{
让myService=sinon.createStubInstance(MyStuff.myService),
controller=new MyStuff.MyController(myService as any,…);
//…在控制器上执行操作
//这就叫myService.amethodweareinterstedin
//如果需要,请验证是否已调用您感兴趣的方法
expect(myService.aMethodWeAreInterestedIn).to.have.been.call;
});
});
我已经完成了,如果您想了解更多关于不同测试双打的信息以及如何在Sinon.js中使用它们,您可能会发现这一点很有用
希望这有帮助
Jan在Typescript中,这可以通过使用sinon.createStubeInstance和sinonSubbedInstance类来实现
例如:
let documentRepository: SinonStubbedInstance<DocumentRepository>;
documentRepository = sinon.createStubInstance(DocumentRepository);
示例断言:
sinon.assert.calledOnce(documentRepository.update);
只有一个地方需要执行类型转换,那就是要进行单元测试的类的初始化
例如:
documentsController =
new DocumentsController(
userContext,
documentRepository as unknown as DocumentRepository);
希望这会有所帮助。
更多关于这个 使用
它允许您:
- 存根对象
- 存根接口
是的,我做了类似的事情。我还了解到我错误地使用了sinon对象,我没有意识到我需要做的只是在调用中使用原始的MyService实例,它使用sinon mock/stubs。不管怎样,你在这里所说的似乎与我的要求相符,谢谢!我又回到了这个问题上,但它似乎不起作用。myServiceMock看起来没有任何方法。有什么想法吗?你有没有给它一个期望<代码>myServiceMock.expected(“doSomething”).returns(42)我试过了,但问题似乎是sinon只能模拟对象的实例,而不能模拟基于构造函数的类型。我想这是有道理的,因为模仿javascript类型会很困难。但是,这让我仍然必须构造这个类的一个实例(将mock传递到ctor中),然后对该实例进行mock。我想不出要做什么,只需要手工创建模拟。你也可以使用import*作为来自“sinon chai”的sinonChai代码>假设您安装了类型:npmi--save dev@types/sinon chai
。
sinon.assert.calledOnce(documentRepository.update);
documentsController =
new DocumentsController(
userContext,
documentRepository as unknown as DocumentRepository);