测试抛出异常的函数

Testing functions that throw exceptions

我正在使用 tape and I'm trying to test a couple of functions. My functions throw errors and validate objects. I like throwing errors because then later my promises can catch them. I'm trying to run simple tests and establishing the data argument in all the scenarios to hit each error in the stack. How can I test this function without putting it in a try / catch every time? I see there's two functions in the API t.throws() and t.doesNotThrow(),我已经尝试过它们,甚至添加了额外的参数,如 t.throws(myFunc({}), Error, "no data"),但似乎没有任何效果。

var test = require('tape')
var _ = require('underscore')

function myFunction(data){
  if(!data) throw new Error("no data")
  if(_.size(data) == 0) throw new Error("data is empty")
  if(!data.date) throw new Error("no data date")
  if(!data.messages.length == 0) throw new Error("no messages")
  data.cake = "is a lie"
  return data
}

test("my function", function(t){
  t.throws(myFunction({}))
  t.end()
}

我对磁带没有忠诚度,也不知道自己在做什么。我只想简单地测试抛出异常的同步函数,而不会产生大量开销。因此,如果这个用例有更好的单元测试框架,我会很乐意使用它。如果磁带有这个能力,我很乐意使用它。

应该这样吗?

test("my function", function(t){
  try{
    myFunction({})
    t.fail()
  }catch(e){
    t.pass(e.message)
  }
  t.end()
})

似乎我无法在 t.throws 的参数中调用该函数,因为它会抛出错误,呃。我相信这是正确的用法。

t.throws(function(){
  myFunction({})
})

您可以像这样使用箭头函数,而不是上面评论中建议的绑定:

t.throws(() => myFunction({}), 'should throw an exception')