测试摩卡的预期失败

bib*_*ibs 18 unit-testing mocha.js node.js

使用Mocha,我试图测试构造函数是否抛出错误.我无法使用expect语法执行此操作,因此我想执行以下操作:

it('should throw exception when instantiated', function() {
  try {
    new ErrorThrowingObject();
    // Force the test to fail since error wasn't thrown
  }
  catch (error) {
   // Constructor threw Error, so test succeeded.
  }
}
Run Code Online (Sandbox Code Playgroud)

这可能吗?

Noa*_*oah 30

should.js

should.js库与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();
  }
});
Run Code Online (Sandbox Code Playgroud)

另外你可以使用should throwError

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

和柴使用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()
});
Run Code Online (Sandbox Code Playgroud)


Mar*_*ark 13

您可以尝试使用Chai的 throw构造.例如:

expect(Constructor).to.throw(Error);
Run Code Online (Sandbox Code Playgroud)


sha*_*unc 11

柴现在有

should.fail()expect.fail()

https://github.com/chaijs/chai/releases/tag/2.1.0


mik*_*ana 8

2017答案如果您需要使用异步代码执行此操作:使用await 而不需要任何其他库.

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)
  }
});
Run Code Online (Sandbox Code Playgroud)

请注意,海报只是在进行同步代码,但我希望很多使用异步的人都会被问题标题带到这里!


Mac*_*ora 5

Mocha默认情况下使用来自node.js(https://nodejs.org/api/assert.html)的Assert。您不需要任何外部库来检查方法是否抛出错误。

声明有一个方法- assert.throws,它具有三个参数,但是这里只有两个参数很重要:

  • 函数-这里传递函数,而不是函数调用
  • 错误-在此处通过或对象构造函数或用于检查错误的函数

假设您有一个名为的函数sendMessage(message),当未设置message参数时会引发错误。功能码:

function sendMessage(message) {
  if (!message || typeof message !== 'string') {
     throw new Error('Wrong message');
  }
  // rest of function
}
Run Code Online (Sandbox Code Playgroud)

好的,因此为了测试它,您需要其他功能来覆盖输入。为什么?因为assert.throws没有任何机会将参数传递给要测试的功能。

所以代替

// WRONG
assert.throws(sendMessage, Error); // THIS IS WRONG! NO POSSIBILITY TO PASS ANYTHING
Run Code Online (Sandbox Code Playgroud)

您需要创建匿名函数:

// CORRECT
assert.throws(() => {
  sendMessage(12);  // usage of wanted function with test parameters
}, Error)
Run Code Online (Sandbox Code Playgroud)

你能看到区别么?我没有直接传递函数,而是将函数调用放在匿名函数内,目的是使用预先准备好的输入进行调用。

第二个参数呢?这取决于应该引发哪种错误,在上面的示例Error中引发了对象,因此我不得不放在那里Error。由于此操作,assert.throws比较抛出的对象是否为相同类型的对象。如果不是Error抛出其他异常,则需要更改此部分。例如,而不是Error我将抛出type的值String

function sendMessage(message) {
  if (!message || typeof message !== 'string') {
     throw 'Wrong message'; // change to String
  }
  // rest of function
}
Run Code Online (Sandbox Code Playgroud)

现在测试电话

assert.throws(() => {
  sendMessage(12); // usage of wanted function with test parameters
}, (err) => err === 'Wrong message')
Run Code Online (Sandbox Code Playgroud)

代替Error第二个参数,我使用了比较功能,以便将抛出的错误与期望值进行比较。


And*_*edo 5

MarkJ 接受的答案是可行的方法,而且比这里的其他人简单得多。让我展示现实世界中的例子:

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: <arg> }', function () {
    expect(new fn('str').arg).to.be.equal('str')
  })
})
Run Code Online (Sandbox Code Playgroud)