Type of test error in chai

I am currently testing my application using chai . I would like to check for an error caused by one of my methods. For this, I wrote this test:

 expect ( place.updateAddress ( [] ) ).to.throw ( TypeError ); 

And here is the method:

 Place.prototype.updateAddress = function ( address ) { var self = this; if ( ! utils.type.isObject ( address ) ) { throw new TypeError ( 'Expect the parameter to be a JSON Object, ' + $.type ( address ) + ' provided.' ); } for ( var key in address ) if ( address.hasOwnProperty ( key ) ) { self.attributes.address[key] = address[key]; } return self; }; 

The problem is that chai does not work in the test, because the method raises a ... TypeError . This should not fail because this is the expected behavior. Here is the statement:

enter image description here

I got around the problem with the following test:

  try { place.updateAddress ( [] ); } catch ( err ) { expect ( err ).to.be.an.instanceof ( TypeError ); } 

But I would prefer to avoid try... catch in my tests, since chai provides built-in methods like throw .

Any idea / suggestion?

+6
source share
1 answer

You need to pass the chai function, but your code passes the result of the function call.

This code should fix your problem:

 expect (function() { place.updateAddress ( [] ); }).to.throw ( TypeError ); 
+8
source

Source: https://habr.com/ru/post/958013/


All Articles