如何在 vitest 中编写预计会出现错误的单元测试

Shu*_*rga 15 javascript unit-testing vitest

我想模拟一个抛出错误的对象方法,但测试总是因这些错误而失败。

我还不能发布图片,但请检查链接。它表明测试失败。

抛出新的错误

下面是我的代码:

工作负载.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.')
    }
}
Run Code Online (Sandbox Code Playgroud)

工作负载.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()
        })
    })
Run Code Online (Sandbox Code Playgroud)

bro*_*eib 16

一般来说,您会用来expect(() => yourFunctionCall()).toThrowError()测试是否抛出异常。(在OP的情况下,还有一个异步函数,其中也必须捕获拒绝。)

文档中的示例:

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$/,
  )
})
Run Code Online (Sandbox Code Playgroud)

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


Ceh*_*iro 4

扔进测试范围就会扔进测试。通常您需要传递一个函数,否则它将就地运行。在 Vitest 中,您可以使用https://vitest.dev/api/#rejects跳过一些样板文件。