英文:
unit test for a function that its argument has type of number
问题
以下是已翻译的代码部分:
const cvssV3Color = (cvssV3: number): any => {
if (cvssV3) {
if ((cvssV3 > 0) && (cvssV3 <= 3.9)) {
return 'low-color';
} else if ((cvssV3 >= 4) && (cvssV3 <= 6.9)) {
return 'medium-color';
} else if ((cvssV3 >= 7) && (cvssV3 <= 8.9)) {
return 'high-color';
} else if ((cvssV3 >= 9) && (cvssV3 <= 10)) {
return 'critical-color';
}
throw new Error("提供的范围无效");
}
};
it("当输入范围的数据类型无效时应抛出错误", () => {
const rangeCondition = '1';
const resultFn = () => {
cvssV3Color(rangeCondition);
}
expect(resultFn).toThrow();
})
请注意,上述代码中的错误消息已由英文翻译为中文。如果您需要进一步的翻译或其他帮助,请告诉我。
英文:
Here is the following function :
const cvssV3Color = (cvssV3: number): any => {
if (cvssV3) {
if ((cvssV3 > 0) && (cvssV3 <= 3.9)) {
return 'low-color'
} else if ((cvssV3 >= 4) && (cvssV3 <= 6.9)) {
return 'medium-color'
} else if ((cvssV3 >= 7) && (cvssV3 <= 8.9)) {
return 'high-color'
} else if ((cvssV3 >= 9) && (cvssV3 <= 10)) {
return 'critical-color'
}
throw new Error("Not valid range is provide")
}
};
I wrote the following test in Vitest+Vue.js 3:
it("Should throw error when type of input range is not valid",()=>{
const rangeCondition = '1'
const resultFn = ()=>{
cvssV3Color(rangeCondition)
}
expect(resultFn).toThrow()
})
I'd like to throw an error when the data type is not valid,But, due to type of inputValue of cvssV3Color in typescript, the typescript shows error type.
How can handle this?
Is is resonable to write a such test for a value that has predifined type?
答案1
得分: 1
你可以使用 @ts-expect-error
。这告诉 TypeScript 编译器,在接下来的代码行中预期会出现一个错误。与使用 @ts-ignore-next-line
不同的是,如果在相应的行中没有错误,它会引发一个错误。
const s = (a: number) => console.log(a)
// @ts-expect-error
s('s')
// @ts-expect-error
s(1)
英文:
You can use @ts-expect-error
. This tells the TS compiler that an error is expected in the following line. It's better than using @ts-ignore-next-line
because it will throw an error if there is no error in the corrosponding line.
const s = (a: number) => console.log(a)
// @ts-expect-error
s('s')
// @ts-expect-error
s(1)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论