Home > Article > Web Front-end > Why Does My Mocha/Chai `expect.to.throw` Assertion Fail to Catch Thrown Errors?
Mocha/Chai expect.to.throw Puzzle: Catching Thrown Errors
Chai's expect.to.throw assertion seems to be elusive in catching thrown errors correctly. Despite writing test cases, the assertions with expect.to.throw repeatedly fail.
To clarify, let's consider the following code snippet:
it('should throw an error if you try to get an undefined property', function (done) { var params = { a: 'test', b: 'test', c: 'test' }; var model = new TestModel(MOCK_REQUEST, params); expect(model.get('z')).to.throw('Property does not exist in model schema.'); expect(model.get('z')).to.throw(new Error('Property does not exist in model schema.')); });
As it turns out, the crux of the issue lies in the manner in which we pass the expression to expect.to.throw.
The Solution: Wrapping the Function
To rectify this problem, we need to pass a function to expect.to.throw, which it will subsequently invoke. The following adjusted code will now work as intended:
it('should throw an error if you try to get an undefined property', function (done) { var params = { a: 'test', b: 'test', c: 'test' }; var model = new TestModel(MOCK_REQUEST, params); 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.')); });
By using the bind method, we create a new function that, when called, will evoke model.get with this set to model and the initial argument set to 'z'.
Explanation of Binding
In this context, bind plays a crucial role. It generates a new function that accepts the same arguments as the original but with a specific value for this when invoked. In our case, the this value is model, and the argument is 'z'.
When we pass the result of model.get('z') to expect.to.throw, we essentially pass the thrown error to the assertion. However, the purpose of expect.to.throw is to check whether an exception is thrown by a given function when called. Therefore, we must pass the function itself rather than its result. The bind method enables us to do just that.
For a deeper dive into bind, refer to the provided link.
The above is the detailed content of Why Does My Mocha/Chai `expect.to.throw` Assertion Fail to Catch Thrown Errors?. For more information, please follow other related articles on the PHP Chinese website!