{"id":668,"hash":"dfe5e92c061c2a541ad09db6cccd06dbb91a6a0e4f42999c84606c0573191bbf","pattern":"How to write a unit test in vitest that expects an error","full_message":"I want to mock an object method that throws an error but the test is always failing with these errors.\n\nI can't post the image yet but please check the link. It shows the test failing.\n\nthrow new Error\n\nHere's my code below:\n\nworkload.js\n\nconst workload = {\n    job: [\n        {workload_1: 'workload 1'}\n    ],\n    createWorkloadJSON: async function(workload){\n        await fsp.appendFile('./workload.json',JSON.stringify(workload))\n        if(fs.existsSync('./workload.json')) return true\n        else throw new Error('workload.json creating failed.')\n    }\n}\n\nworkload.test.js\n\ndescribe('workload', ()=>{\n    afterEach(()=>{\n        vi.restoreAllMocks()\n    })\n    \n     it('throws an error when workload.json is not found', async ()=>{\n            const spy = vi.spyOn(workload, 'createWorkloadJSON').mockImplementation(async()=>{\n                throw new Error('workload.json creating failed.')\n            })\n            expect(await workload.createWorkloadJSON()).toThrow(new Error('workload.json creating failed.'))\n            expect(spy).toHaveBeenCalled()\n        })\n    })","ecosystem":"npm","package_name":"unit-testing","package_version":null,"solution":"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/expect.html#rejects to skip some boilerplate.","confidence":0.95,"source":"stackoverflow","source_url":"https://stackoverflow.com/questions/74487468/how-to-write-a-unit-test-in-vitest-that-expects-an-error","votes":31,"created_at":"2026-04-19T04:51:28.848696+00:00","updated_at":"2026-04-19T04:51:28.848696+00:00"}