Search code examples
angularjsunit-testingtypescriptmocha.jssinon-chai

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


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.


Solution

  • 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)