Mocha / Chai expect.to.throw not catching thrown errors

前端 未结 7 1933
傲寒
傲寒 2020-11-22 07:20

I\'m having issues getting Chai\'s expect.to.throw to work in a test for my node.js app. The test keeps failing on the thrown error, but If I wrap the test case

7条回答
  •  时光取名叫无心
    2020-11-22 08:09

    You have to pass a function to expect. Like this:

    expect(model.get.bind(model, 'z')).to.throw('Property does not exist in model schema.');
    expect(model.get.bind(model, 'z')).to.throw(new Error('Property does not exist in model schema.'));
    

    The way you are doing it, you are passing to expect the result of calling model.get('z'). But to test whether something is thrown, you have to pass a function to expect, which expect will call itself. The bind method used above creates a new function which when called will call model.get with this set to the value of model and the first argument set to 'z'.

    A good explanation of bind can be found here.

提交回复
热议问题