Home > Enterprise >  How to write a unit test in vitest that expects an error
How to write a unit test in vitest that expects an error

Time:11-18

I want to mock an object method that throws an error but the test is always failing with these errors.

I can't post the image yet but please check the link. It shows the test failing.

throw new Error

Here's my code below:

workload.js

const workload = {
    job: [
        {workload_1: 'workload 1'}
    ],
    createWorkloadJSON: async function(workload){
        await fsp.appendFile('./workload.json',JSON.stringify(workload))
        if(fs.existsSync('./workload.json')) return true
        else throw new Error('workload.json creating failed.')
    }
}

workload.test.js

describe('workload', ()=>{
    afterEach(()=>{
        vi.restoreAllMocks()
    })
    
     it('throws an error when workload.json is not found', async ()=>{
            const spy = vi.spyOn(workload, 'createWorkloadJSON').mockImplementation(async()=>{
                throw new Error('workload.json creating failed.')
            })
            expect(await workload.createWorkloadJSON()).toThrow(new Error('workload.json creating failed.'))
            expect(spy).toHaveBeenCalled()
        })
    })

CodePudding user response:

Throwing in the test scope will throw in the test. Generally you need to pass a function instead, otherwise it will run in place. In Vitest you can use https://vitest.dev/api/#rejects to skip some boilerplate.

  • Related