Test for expected failure in Mocha

后端 未结 9 1983
终归单人心
终归单人心 2020-12-10 01:29

Using Mocha, I am attempting to test whether a constructor throws an error. I haven\'t been able to do this using the expect syntax, so I\'d like to do the following:

<
9条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-10 02:32

    should.js

    Using the should.js library with should.fail

    var should = require('should')
    it('should fail', function(done) {
      try {
          new ErrorThrowingObject();
          // Force the test to fail since error wasn't thrown
           should.fail('no error was thrown when it should have been')
      }
      catch (error) {
       // Constructor threw Error, so test succeeded.
       done();
      }
    });
    

    Alternative you can use the should throwError

    (function(){
      throw new Error('failed to baz');
    }).should.throwError(/^fail.*/)
    

    Chai

    And with chai using the throw api

    var expect = require('chai').expect
    it('should fail', function(done) {
      function throwsWithNoArgs() {
         var args {} // optional arguments here
         new ErrorThrowingObject(args)
      }
      expect(throwsWithNoArgs).to.throw
      done()
    });
    

提交回复
热议问题