最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do I test with jest that a list of Enums in TypeScript has all the string values? - Stack Overflow

programmeradmin0浏览0评论

I have a list of enums:

export enum Hobbies {
   Paint = 'PAINT',
   Run = 'RUN',
   Bike = 'BIKE',
   Dance = 'DANCE'
}

I'd like to loop through this in Jest and assert that all the string values are there, maybe along with each key too? This is in case a value is null/missing and that could affect the behavior of a UI render.

I was thinking import the list, and assert that each value is not null. But do I use a test.each()? This list is actually much longer.

I know enums shouldn't need a test like this but in this case it is useful.

I have a list of enums:

export enum Hobbies {
   Paint = 'PAINT',
   Run = 'RUN',
   Bike = 'BIKE',
   Dance = 'DANCE'
}

I'd like to loop through this in Jest and assert that all the string values are there, maybe along with each key too? This is in case a value is null/missing and that could affect the behavior of a UI render.

I was thinking import the list, and assert that each value is not null. But do I use a test.each()? This list is actually much longer.

I know enums shouldn't need a test like this but in this case it is useful.

Share Improve this question edited May 29, 2021 at 21:45 jonrsharpe 122k30 gold badges268 silver badges476 bronze badges asked May 29, 2021 at 20:33 John McGellanJohn McGellan 911 silver badge7 bronze badges 3
  • 1 To remend the best approach, it might be helpful to know why a test like this is useful in your case. As you imply, it is invariably true that an enum's keys exist and have their values. Do you want to guard against future deletions of keys or changes to values? – kdau Commented May 29, 2021 at 21:01
  • This should have been covered by TS. It will cause an error if a key in use isn't there, won't it? – Estus Flask Commented May 29, 2021 at 22:52
  • @kdau Yes that's correct. It is quite a long list so I want to guard it against future possible changes to the values. How might I go about writing the test for this? – John McGellan Commented Jun 1, 2021 at 4:51
Add a ment  | 

1 Answer 1

Reset to default 3

Use Property Matchers of snapshot testing. Whenever the enumeration value changes, the test will fail if the two snapshots do not match.

E.g.

index.ts:

export enum Hobbies {
  Paint = 'PAINT',
  Run = 'RUN',
  Bike = 'BIKE',
  Dance = 'DANCE',
}

index.test.ts:

import { Hobbies } from './';

describe('67755520', () => {
  it('should pass', () => {
    expect(Hobbies).toMatchInlineSnapshot(`
      Object {
        "Bike": "BIKE",
        "Dance": "DANCE",
        "Paint": "PAINT",
        "Run": "RUN",
      }
    `);
  });
});

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论