如何在 Typescript 中使用 Sinon? [英] How do I use Sinon with Typescript?

查看:39
本文介绍了如何在 Typescript 中使用 Sinon?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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

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

sinon 可以与 Typescript 一起使用吗?

Can sinon be used with Typescript?

推荐答案

您可能需要使用 类型断言来使类型变宽,然后再将其缩小到您的特定类型:

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

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

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

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

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

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

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

If you want automatically created fakes, you can grab the FakeFactory from 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).

FakeFactory 的使用示例:

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

这篇关于如何在 Typescript 中使用 Sinon?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆