Home > Software engineering >  Jest test Typescript type as object
Jest test Typescript type as object

Time:01-11

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?

CodePudding user response:

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

  • Related