函数的单元测试,其参数的类型为数字。

huangapple go评论76阅读模式
英文:

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 =&gt; {
    if (cvssV3) {
        if ((cvssV3 &gt; 0) &amp;&amp; (cvssV3 &lt;= 3.9)) {
            return &#39;low-color&#39;
        } else if ((cvssV3 &gt;= 4) &amp;&amp; (cvssV3 &lt;= 6.9)) {
            return &#39;medium-color&#39;
        } else if ((cvssV3 &gt;= 7) &amp;&amp; (cvssV3 &lt;= 8.9)) {
            return &#39;high-color&#39;
        } else if ((cvssV3 &gt;= 9) &amp;&amp; (cvssV3 &lt;= 10)) {
            return &#39;critical-color&#39;
        }
        throw new Error(&quot;Not valid range is provide&quot;)

    }
};

I wrote the following test in Vitest+Vue.js 3:

it(&quot;Should throw error when type of input range is not valid&quot;,()=&gt;{

        const rangeCondition = &#39;1&#39;

        const resultFn = ()=&gt;{
            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 不同的是,如果在相应的行中没有错误,它会引发一个错误。

playground

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.

playground

const s = (a: number) =&gt; console.log(a)

// @ts-expect-error
s(&#39;s&#39;)

// @ts-expect-error
s(1)

huangapple
  • 本文由 发表于 2023年1月9日 13:34:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/75053503.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定