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

I have a list of enums:export enum Hobbies {Paint = 'PAINT',Run = 'RUN',Bike = �

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",
      }
    `);
  });
});

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745492446a4630045.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信