Home  >  Article  >  Web Front-end  >  Why Does `expect.to.throw` Fail to Catch Thrown Errors in Mocha/Chai Tests?

Why Does `expect.to.throw` Fail to Catch Thrown Errors in Mocha/Chai Tests?

Linda Hamilton
Linda HamiltonOriginal
2024-11-17 11:53:01799browse

Why Does `expect.to.throw` Fail to Catch Thrown Errors in Mocha/Chai Tests?

Mocha / Chai expect.to.throw Doesn't Catch Thrown Errors?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn