【问题标题】:Mocha/Chai: Test for exact throw error resultMocha/Chai:测试精确的抛出错误结果
【发布时间】:2017-11-14 21:40:15
【问题描述】:

有一个简单的方法,会报错:

methods.js

insertItem = new ValidatedMethod({
    name    : 'article.insert.item',
    validate: new SimpleSchema({
        parent: { type: SimpleSchema.RegEx.Id }
        value : { type: String }
    }).validator(),

    run({ parent, value}) {
        var isDisabled = true
        if (isDisabled)
            throw new Meteor.Error('example-error', 'There is no reason for this error :-)')
    }
})

现在我想针对这个错误进行 mocha 测试。所以我想出了这个,它正在工作:

server.test.js

it('should not add item, if element is disabled', (done) => {
    const value = 'just a string'

    function expectedError() {
        insertItem.call(
            {
                parent: '12345',
                value
            }
        )
    }

    expect(expectedError).to.throw
    done()
})

到目前为止一切正常。

问题

但我想测试一下确切的错误信息。

我已经试过了

expect(expectedError).to.throw(new Meteor.Error('example-error', 'There is no reason for this error :-)'))

但它给了我一个失败的测试:

Error: expected [Function: expectedError] to throw 'Error: There is no reason for this error :-) [example-error]'

【问题讨论】:

    标签: javascript unit-testing meteor mocha.js chai


    【解决方案1】:

    我从this post发现我需要这样写:

    expect(expectedError).to.throw(Meteor.Error(), 'example-error', 'This is an error');
    

    注意错误信息在Error()之后,

    【讨论】:

    • 我发现第二个字符串似乎没有被检查,所以最好写成expect(expectedError).to.throw(Meteor.Error(), 'example-error') ;
    【解决方案2】:

    我认为文档对此有点误导/混淆 - 只需从您的 expect 中删除 new 运算符,它就会与抛出的错误相匹配:

    expect(expectedError).to.throw(Meteor.Error('example-error', 'There is no reason for this error :-)'))

    【讨论】:

    • 另外,你在下一行有var disabled = trueif (isDisabled) - 但我假设这只是示例代码,没有从你的函数中复制
    • 这样测试仍然失败:Error: expected [Function: expectedError] to throw an error
    • @user3142695 我已经用你的示例代码测试了上面几次,它抛出了正确的错误。你们是否都删除了new 并更改了var disabled / if(isDisabled) 部分?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-04
    • 1970-01-01
    相关资源
    最近更新 更多