测试抛出异常的函数

Tho*_*ggi 4 javascript testing error-handling unit-testing node.js

我正在使用磁带,我正在尝试测试几个功能.我的函数抛出错误并验证对象.我喜欢抛出错误,因为后来我的承诺可以抓住它们.我正在尝试运行简单的测试并data在所有场景中建立 参数来命中堆栈中的每个错误.如何在不将其放入try / catch每次的情况下测试此功能?我看到有API中的两个函数t.throws()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()
}
Run Code Online (Sandbox Code Playgroud)

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

这是怎么做的?

test("my function", function(t){
  try{
    myFunction({})
    t.fail()
  }catch(e){
    t.pass(e.message)
  }
  t.end()
})
Run Code Online (Sandbox Code Playgroud)

Tho*_*ggi 6

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

t.throws(function(){
  myFunction({})
})
Run Code Online (Sandbox Code Playgroud)