Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Jest test Typescript type as object

Say I have the following type:

export type Events = {
  LOGIN: undefined
  NAVIGATION: {
    screen: string
  }
  SUPPORT: {
    communication_method: 'chat' | 'email' | 'phone'
  }
}

then I would like to make a test that ensures I do not write a type "key" more than 45 characters.

     it('is compliant to event limitations', () => {
        Object.keys(Events).forEach((key) => {
          expect(key.length).toBeLessThan(45)
     })

of course TS complains 'Events' only refers to a type, but is being used as a value here. but is there an elegant way to ‘convert’ it to an value?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The Types in TypeScript are used only in compile time and removed during the runtime.

When you run your program there will be no type Events in your source.

Your code:

export type Events = {
  LOGIN: undefined
  NAVIGATION: {
    screen: string
  }
  SUPPORT: {
    communication_method: 'chat' | 'email' | 'phone'
  }
}

will compile to JS to nothing (type will be removed).

If you have a variable that uses this type you can check that

export type Events = {
  LOGIN: undefined
  NAVIGATION: {
    screen: string
  }
  SUPPORT: {
    communication_method: 'chat' | 'email' | 'phone'
  }
}

const myVar: Events = {...}

Then you can check that variable:

it('is compliant to event limitations', () => {
    Object.keys(myVar).forEach((key) => {
    expect(key.length).toBeLessThan(45)
})

Another way it to use custom transformer library like ts-transformer-keys

I’ll not recommend doing, though, but here is it for completeness.

import { keys } from 'ts-transformer-keys';

export type Events = {
  LOGIN: undefined
  NAVIGATION: {
    screen: string
  }
  SUPPORT: {
    communication_method: 'chat' | 'email' | 'phone'
  }
}
const eventKeys = keys<Events>();

console.log(eventKeys); // ['id', 'name', 'age']
it('is compliant to event limitations', () => {
    Object.keys(eventKeys).forEach((key) => {
    expect(key.length).toBeLessThan(45)
})

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading