Test for expected failure in Mocha

后端 未结 9 1978
终归单人心
终归单人心 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:26

    MarkJ's accepted answer is the way to go and way simpler than others here. Let me show example in real world:

    function fn(arg) {
      if (typeof arg !== 'string')
        throw TypeError('Must be an string')
    
      return { arg: arg }
    }
    
    describe('#fn', function () {
      it('empty arg throw error', function () {
        expect(function () {
          new fn()
        }).to.throw(TypeError)
      })
    
      it('non-string arg throw error', function () {
        expect(function () {
          new fn(2)
        }).to.throw(TypeError)
      })
    
      it('string arg return instance { arg:  }', function () {
        expect(new fn('str').arg).to.be.equal('str')
      })
    })
    

提交回复
热议问题