How to unit-test an object that contain a type union using typescript, karma and sinon?

心已入冬 提交于 2019-12-13 02:47:33

问题


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;
};

And PaymentFrequency type is defined as:

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

In the controller,

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 gave me the error as "type string is not assignable to type paymentFrequency". Let me know if there's a way to handle it.


回答1:


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

refer this for explanation

Example:

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)



回答2:


It's always possible to disable type checks in tests with <any> type casting when needed, but it's not the case. In fact, typing system will detect a mistake here, Monthly isn't MONTHLY and certainly isn't compatible with PaymentFrequency.

let solution = { _id: 'aa0', paymentFrequency: 'MONTHLY', ....};

will result in inferred solution type, { _id: string, paymentFrequency: string }. The information that paymentFrequency is actually MONTHLY is lost, paymentFrequency isn't compatible with and PaymentFrequency, and solution is no longer compatible with ISolution.

It should be:

let solution: ISolution = { _id: 'aa0', paymentFrequency: 'MONTHLY', ....};


来源:https://stackoverflow.com/questions/49192377/how-to-unit-test-an-object-that-contain-a-type-union-using-typescript-karma-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!