Chai expect .to.throw(Error) 没有按预期工作

Chai expect .to.throw(Error) not working as expected

我的断言是:

    it.only('should throw an error if the transcription cannot happen', () => {
        expect(TranscriptLib.myFunc({ data }, '1')).to.throw(Error)
    })

我的函数是:

myFunc: (data, id) => {

                throw new Error({
                    message: 'Transcription failed',
                    error: someError
                })

然而,当我运行我的测试时,日志显示:

     Error: [object Object]

测试失败。我做错了什么?

您的问题与 Mocha / Chai expect.to.throw not catching thrown errors

重复

解决问题的最直接方法是从箭头函数调用代码:

it.only('should throw an error if the transcription cannot happen', () => {   
  expect(() => TranscriptLib.myFunc({ data }, '1')).to.throw(Error)
})

如另一个问题的答案所示,您还可以使用 .bind 创建新函数,依此类推。