简体   繁体   English

Mocha / Chai:测试精确的投掷错误结果

[英]Mocha/Chai: Test for exact throw error result

There is a simple method, which throws an error: 有一个简单的方法,它会抛出一个错误:

methods.js 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 :-)')
    }
})

Now I want to do a mocha test for this error. 现在我想对这个错误做一个mocha测试。 So I came up with this, which is working: 所以我提出了这个,这是有效的:

server.test.js 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()
})

Until this point everything is working. 在此之前一切正常。

The problem 问题

But I would like to test for the exact error message. 但我想测试确切的错误消息。

I already tried 我已经试过了

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

But it gives me a failing test: 但它给了我一个失败的测试:

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

我认为这些文档在这方面有点误导/混淆 - 只需从您的expect删除new运算符,它将与抛出的错误相匹配:

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

I found from this post that I needed to write it like this: 我在这篇文章中发现我需要像这样写:

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

Note that the error messages are after the Error(), 请注意,错误消息位于Error()之后,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM