3

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]'
user3142695
  • 15,844
  • 47
  • 176
  • 332

2 Answers2

0

I think the docs are a bit misleading/confusing on this - just remove the new operator from your expect and it'll match the error thrown:

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

rubie
  • 1,906
  • 2
  • 20
  • 26
  • Also, you've got `var disabled = true` BUT `if (isDisabled)` in the next line - but I'm assuming this is just example code not copied from your function – rubie Jun 13 '17 at 08:56
  • With this the test is still failing: `Error: expected [Function: expectedError] to throw an error` – user3142695 Jun 13 '17 at 09:41
  • @user3142695 I've tested the above a couple of times with your example code and it throws the correct error. Have you both removed the `new` and changed the `var disabled` / `if(isDisabled)` parts? – rubie Jun 13 '17 at 10:27
0

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

Little Brain
  • 2,647
  • 1
  • 30
  • 54
  • I'm finding that the second string seems not to be checked, so it is probably better to write expect(expectedError).to.throw(Meteor.Error(), 'example-error'); – Little Brain Apr 02 '19 at 11:07