如何使用打字稿,业力和sinon对包含类型联合的对象进行单元测试? [英] How to unit-test an object that contain a type union using typescript, karma and sinon?

查看:98
本文介绍了如何使用打字稿,业力和sinon对包含类型联合的对象进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在对带有角框架的打字稿编写的项目进行单元测试,方法是将缘故与mocha和chai框架一起应用.对象的接口为:

I'm doing unit-testing for a project which is written in typescript with angular framework, by applying karma with mocha and chai frameworks. And there's an interface for the object as:

interface ISolution {
    _id: string;
    paymentFrequency: PaymentFrequency;
};

而PaymentFrequency类型定义为:

And PaymentFrequency type is defined as:

type PaymentFrequency = 'MONTHLY' | 'ANNUAL' | 'SINGLE';

在控制器中,

open(solution: ISolution) { };

问题是当我尝试将解决方案模拟为:

The problem is when I tried to mock the solution as:

let solution = { _id: 'aa0', paymentFrequency: 'MONTHLY', ....};
let spy = sandbox.stub(controller, 'open').withArgs(solution);

Typescript给我错误,因为类型字符串不可分配给类型PaymentFrequency".让我知道是否有办法处理.

Typescript gave me the error as "type string is not assignable to type paymentFrequency". Let me know if there's a way to handle it.

推荐答案

您可以尝试使用以下每种类型成为接口.因为这将严格执行类型检查.

You can try using following each type becomes a interface. Because instead of any this will strict the type checking.

请参考此内容进行解释

示例:

interface ISolution {
    _id: string;
    paymentFrequency: monthly | annual | single
};

interface monthly{
    kind:"MONTHLY"
}
interface annual{
    kind:"ANNUAL"
}
interface single{
    kind:"SINGLE"
}


var fun=(obj:ISolution)=>{
 console.log("hererer",obj)
} 
var y:monthly={kind : "MONTHLY"}
var x= { _id: 'aa0', paymentFrequency:y}
fun(x)

这篇关于如何使用打字稿,业力和sinon对包含类型联合的对象进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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