Test for expected failure in Mocha

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

    2017 answer if you need to do this with async code: using await and not needing any other libraries.

    it('Returns a correct error response when making a broken order', async function(){
      this.timeout(5 * 1000);
      var badOrder = {}
      try {
        var result = await foo.newOrder(badOrder)
        // The line will only be hit if no error is thrown above!
        throw new Error(`Expected an error and didn't get one!`)
      } catch(err) {
        var expected = `Missing required field`
        assert.equal(err.message, expected)
      }
    });
    

    Note the poster was only doing sync code, but I expect a lot of people using async were led here by the question title!

提交回复
热议问题