如何使用 chai 和 mocha 验证抛出的 javascript 异常?

How to validate thrown javascript exception using chai and mocha?

我有 MongoDB 验证查询参数的查询函数 这是功能 注意:用户是猫鼬模型

function fetchData(uName)
{
    try{
        if(isParamValid(uName))
        {
            return user.find({"uName":uName}).exec()
        }
        else {
            throw "Invalid params"
        }
    }
    catch(e)
    {
        throw e
    }
}

为了使用无效的用户名值进行测试,我已经使用 mocha、chai 和 chai-as-promised 为基于 promise 的函数编写了测试代码

describe('Test function with invalid values', async ()=>{
    it('should catch exception', async () => {
        await expect(fetchData(inValidUserName)).to.throw()
    })

    it('should catch exception', async () => {
        await expect(fetchData(inValidUserName)).to.throw(Error)
    })

    it('should catch exception', async () => {
        await expect(fetchData(inValidUserName)).to.be.rejectedWith(Error)
    })

    it('should catch exception', async () => {
        await expect(fetchData(inValidUserName)).to.be.rejected
    })
})

None 他们通过了测试,如何编写测试用例来处理无效用户名值的异常

您正在将 fetchData 函数调用的结果传递给 expect 函数。不要在 expect 函数中调用 fetchData 函数,而是将函数传递给 expect 函数。

it('should catch exception', async () => {
    await expect(() => fetchData(inValidUserName)).to.throw('Invalid params')
})

使用try/catch

it('should catch exception', async () => {
    try {
      await fetchData(inValidUserName);
    } catch(error) {
      expect(error).to.exist;
    }
})