【问题标题】:How can I make a Jest test ensure that a value is in an enum?开玩笑测试以确保一个值在 ENUM 中
【发布时间】:2022-10-06 17:08:03
【问题描述】:
这是我第一次与 jest 合作。我有一个场景,我想查看所选值是否在 ENUM 中。这是我的测试用例:
test(\'Should be valid\', () => {
expect(TestCasesExport.userAccStatus(ACC_STATUS.LIVE)).toContain(MEM_STATUS);
});
MEM_STATUS 是一个枚举,ACC_STATUS 是另一个枚举,它与 MEM_STATUS 有一些共同的值。
当我运行这个测试时已收到是\'live\',预期是一个对象,即{\"LIVE\": \"live\", ...}。
那么,我应该在我的测试用例中进行哪些更改以确保已收到枚举中存在值MEM_STATUS?
标签:
typescript
enums
jestjs
ts-jest
【解决方案1】:
我有完全相同的问题。检查对象值expect.any(SomeEnum) 将失败,并显示:
TypeError: Right-hand side of 'instanceof' is not callable'
希望 jest 将来能改善这一点,但是这里有一个解决方法允许您确保值在枚举中:
// We can't do expect.any(Currency)
// So check the value is in the enum (as an Object)'s values
// See https://stackoverflow.com/questions/73697466/jest-test-to-ensure-that-a-value-is-in-an-enum
const knownCurrencies = Object.values(Currency);
expect(knownCurrencies.includes(currency));
在其他地方(例如在对象值测试中),您只需要测试该值是否为数字,但前面的代码将确保它出现在枚举中。
expect(lastTransaction).toEqual({
...
// expect.any(Currency) won't work
currency: expect.any(Number),
...
});