Home > Back-end >  How to verify for a specific type using Chai expect() in Typescript?
How to verify for a specific type using Chai expect() in Typescript?

Time:01-25

I've tried looking for an answer in previous posts, but I havnt found one so here it is:

I am currently trying to test the returned type of an Object instance property value using expect() from Chai in Typescript. So far, I've tried this:

/* My type file */

export type customType = "one" | "two" | "three";
export default customType;

/* My test file */

import customType from '{path_to_customType}'; // 'customType' is declared but its value is never read.

const newObject = new Object({property1: value1}) //note: value1 is of type customType

describe("Class1 test", () => {
    it('my tests', () => {
        expect(newObject).to.have.property("property1").to.equal("value1"); //so far, this one works fine
        expect(newObject).to.be.a('customType'); // not working
        expect(newObject).to.be.an('customType'); // not working
        expect(newObject).to.be.a(customType); // not working
        expect(newObject).to.be.an(customType); // not working
        expect(typeof newObject.getProperty1()).to.equal('customType'); // not working
        expect(newObject).to.be.an.instanceof(customType); // not working
        expect(newObject).to.be.an.instanceof('customType'); // not working
        assert.typeOf(newObject.getProperty1(), 'customType'); // not working
        assert.typeOf(newObject.getProperty1(), customType); // not working
    });
});

As you can see, value1 is supposed to be of type customType but it gives me an error since customType is never read. How can I verify if my value is of a specific custom type?

**Note: in my Object definition, the property property1 is specified of type customType

*UPDATE I just noticed the returned type of value1 is 'string' as if the type is only an alias... How can I test that then ?

CodePudding user response:

TypeScript's type system is purely a compile-time feature. Running code doesn't have types. You can use typeof to test whether values are boolean, number, string, object, etc., and you can also test whether an Object is an instance of a class.

Your customType, however, simply isn't something that can be checked at runtime. Once the code has been converted into JavaScript in order to run, customType is just a string like any other string.

  •  Tags:  
  • Related