简体   繁体   中英

Mocha/Chai: Test for exact throw error result

There is a simple method, which throws an error:

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. So I came up with this, which is working:

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(),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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