In your node.js tests, you're experiencing difficulties utilizing Chai's expect.to.throw to detect thrown errors. The tests consistently fail, reporting the thrown error. However, if you encapsulate the test in a try-catch block and assert on the captured error, the test passes.
Is expect.to.throw not functioning as anticipated?
To resolve this issue, you need to pass a function to expect, not the result of the function call:
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.'));
In your original approach, you were passing the result of calling model.get('z') to expect. To test whether a function throws an error, you must provide a function for expect to call itself. The bind method creates a new function that, when called, invokes model.get with the expected arguments.
Refer to the provided documentation for further clarification on the bind method.
The above is the detailed content of Why Does `expect.to.throw` Fail to Catch Thrown Errors in Mocha/Chai Tests?. For more information, please follow other related articles on the PHP Chinese website!