Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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()
        })
    })
like image 705
Shu Pesmerga Avatar asked Sep 04 '25 03:09

Shu Pesmerga


1 Answers

In general you'd use expect(() => yourFunctionCall()).toThrowError() to test for an exception being thrown. (In the OP's case, there was also an async function where the reject had to be captured too.)

Example from the docs:

import { expect, test } from 'vitest'

function getFruitStock(type) {
  if (type === 'pineapples')
    throw new DiabetesError('Pineapples are not good for people with diabetes')

  // Do some other stuff
}

test('throws on pineapples', () => {
  // Test that the error message says "diabetes" somewhere: these are equivalent
  expect(() => getFruitStock('pineapples')).toThrowError(/diabetes/)
  expect(() => getFruitStock('pineapples')).toThrowError('diabetes')

  // Test the exact error message
  expect(() => getFruitStock('pineapples')).toThrowError(
    /^Pineapples are not good for people with diabetes$/,
  )
})

https://vitest.dev/api/expect.html#tothrowerror

like image 196
broc.seib Avatar answered Sep 07 '25 18:09

broc.seib