【问题标题】:How to validate thrown javascript exception using chai and mocha?如何使用 chai 和 mocha 验证抛出的 javascript 异常?
【发布时间】:2020-08-29 15:35:57
【问题描述】:

我有 MongoDB Query 函数,其中验证了查询参数 这是功能 注意:用户是猫鼬模型

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 编写了测试代码

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
    })
})

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

【问题讨论】:

    标签: javascript node.js mocha.js chai chai-as-promised


    【解决方案1】:

    使用try/catch

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

    【讨论】:

    • 此解决方案不起作用。因为在这种情况下,如果 fetchData 函数没有为 invalidValues 抛出异常/错误,它仍然会通过测试用例
    【解决方案2】:

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

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

    【讨论】:

    • 感谢您的回答,它对我有用 如果我将 throw new Error("Invalid params") 从 throw "Invalid params" 中替换,我是否需要更改测试代码??
    • 我认为您不需要更改任何内容
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-08
    • 2013-06-29
    • 1970-01-01
    • 2013-09-26
    • 2010-10-21
    • 2021-01-21
    相关资源
    最近更新 更多