如何在 Typescript 中使用 Sinon?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28156057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 06:34:58  来源:igfitidea点击:

How do I use Sinon with Typescript?

unit-testingtypescriptsinon

提问by Brandon

If I use sinon with typescript then how do I cast the sinon mock to an instance of my object?

如果我将 sinon 与 typescript 一起使用,那么如何将 sinon 模拟转换为我的对象实例?

For instance a SinonMock would be returned but my controller under test may require a specific service passed in to its constructor.

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

var myServiceMock: MyStuff.MyService = <MyStuff.MyService (sinon.mock(MyStuff.MyService));

controllerUnderTest = new MyStuff.MyController(myServiceMock, $log);

Can sinon be used with Typescript?

sinon 可以与 Typescript 一起使用吗?

采纳答案by Fenton

You may need to use an <any>type assertion to make the type wide before you narrow it to your specific type:

<any>在将类型缩小到特定类型之前,您可能需要使用类型断言使类型变宽:

var myServiceMock: MyStuff.MyService = 
    <MyStuff.MyService> <any> (sinon.mock(MyStuff.MyService));

Just to clarify one behaviour of sinon - although you pass in MyStuff.MyService, whatever you pass to the mockmethod is only used to provide better error messages.

只是为了澄清 sinon 的一种行为 - 尽管您传入MyStuff.MyService,但您传递给该mock方法的任何内容仅用于提供更好的错误消息。

If you want the mock to have methods and properties, you need to add them.

如果您希望模拟具有方法和属性,则需要添加它们

If you want automatically created fakes, you can grab the FakeFactoryfrom tsUnit, which creates a fake version with some default values that you can opt to override - in JavaScript this is pretty easy stuff (plus by not using too much mock functionality, you can ensure you are testing behaviour rather than implementation).

如果你想自动创建假货,你可以FakeFactorytsUnit 中获取,它会创建一个带有一些默认值的假版本,你可以选择覆盖这些默认值 - 在 JavaScript 中这是非常简单的东西(加上不使用太多的模拟功能,你可以确保您正在测试行为而不是实现)。

Example use of FakeFactory:

使用示例FakeFactory

var target = tsUnit.FakeFactory.getFake<RealClass>(RealClass);
var result = target.run();
this.areIdentical(undefined, result);

回答by Jan Molak

Sinon can create a stub based on a constructor quite easily if, instead of mock, you use the createStubInstancemethod.

如果mock您使用该createStubInstance方法而不是 ,Sinon 可以很容易地创建基于构造函数的存根。

An example using mocha, chai, sinonand sinon-chai, could look like this:

使用mochachaisinonsinon-chai的示例可能如下所示:

import * as sinon from 'sinon';
import * as chai from 'chai';

// ... imports for the classes under test

const expect    = chai.expect;
const sinonChai = require("sinon-chai");

chai.use(sinonChai);

describe('MyController', () => {
    it('uses MyService', () => {

        let myService  = sinon.createStubInstance(MyStuff.MyService),
            controller = new MyStuff.MyController(myService as any, ...);

        // ... perform an action on the controller 
        // that calls myService.aMethodWeAreInterestedIn

        // verify if the method you're interested in has been called if you want to
        expect(myService.aMethodWeAreInterestedIn).to.have.been.called;
    });
});

I've published an article, which you might find useful if you'd like to learn more about the different test doubles and how to use them with Sinon.js.

发表了一篇文章,如果您想了解更多有关不同测试替身以及如何将它们与 Sinon.js 一起使用的信息,您可能会发现这篇文章很有用。

Hope this helps!

希望这可以帮助!

Jan

回答by Milos Josic

In Typescript this can be achieved by using sinon.createStubInstance and SinonStubbedInstance class.

在 Typescript 中,这可以通过使用 sinon.createStubInstance 和 SinonStubbedInstance 类来实现。

Example:

例子:

let documentRepository: SinonStubbedInstance<DocumentRepository>;

documentRepository = sinon.createStubInstance(DocumentRepository);

Now you have a full intellisense for working with all stubbed methods of this class.

现在你有了一个完整的智能感知来处理这个类的所有存根方法。

Example Arrange:

示例排列:

documentRepository.delete.resolves({deletedCount: 1});

documentRepository.update.throws(error);

Example Assert:

示例断言:

sinon.assert.calledOnce(documentRepository.update);

There is only one place where you would need to perform type casting and that is the initiallization of the class you want to unit test.

只有一个地方需要执行类型转换,那就是要进行单元测试的类的初始化。

Example:

例子:

documentsController =
  new DocumentsController(
    userContext,
    documentRepository as unknown as DocumentRepository);

Hope this will help. More on this article.

希望这会有所帮助。更多关于这篇文章

回答by Matt Wynne

Use ts-sinon.

使用ts-sinon

It lets you:

它让你:

  • stub objects
  • stub interfaces
  • 存根对象
  • 存根接口