Home > Blockchain >  unit test for a function that its argument has type of number
unit test for a function that its argument has type of number

Time:01-09

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?

CodePudding user response:

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) => console.log(a)

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

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