我正在使用Jest为Node.js后端开发一些测试,我需要查看来自第三方的一些值。在某些情况下,这些值可以是boolean
或null
。
现在我正在检查符合这种情况的变量:
expect(`${variable}`).toMatch(/[null|true|false]/);
有没有更好的方法来使用Jest内置函数检查它们?
答案 0 :(得分:2)
怎么样?
expect(variable === null || typeof variable === 'boolean').toBeTruthy();
您可以使用expect.extend将其添加到内置匹配器中:
expect.extend({
toBeBooleanOrNull(received) {
return received === null || typeof received === 'boolean' ? {
message: () => `expected ${received} to be boolean or null`,
pass: true
} : {
message: () => `expected ${received} to be boolean or null`,
pass: false
};
}
});
并使用它:
expect(variable).toBeBooleanOrNull();