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
1 Answer
Reset to default 3Use 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条)