Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unit testing 如何将Sinon与Typescript一起使用?_Unit Testing_Typescript_Sinon - Fatal编程技术网

Unit testing 如何将Sinon与Typescript一起使用?

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

如果我将sinon与typescript一起使用,那么如何将sinon模拟投射到我的对象实例

例如,将返回SinonMock,但我的被测控制器可能需要将特定服务传递给其构造函数

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)import*作为来自“sinon chai”的sinonChai假设您安装了类型:
npmi--save dev@types/sinon chai
sinon.assert.calledOnce(documentRepository.update);
documentsController =
  new DocumentsController(
    userContext,
    documentRepository as unknown as DocumentRepository);