问题
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