【问题标题】:How can I get Jasmine in CoffeeScript to test for exceptions?如何在 CoffeeScript 中获取 Jasmine 来测试异常?
【发布时间】:2012-08-19 14:02:09
【问题描述】:

我有这个代码:

class root.Goal
    constructor: (@name, @size) ->
        if @size <= 0 then throw new Error "Goal must be larger than 0 size"

由 Jasmine-CoffeeScript 测试测试:

it "cannot be of size 0", ->
    expect(new p.Goal("Goal 3", 0)).toThrow "Goal must be larger than 0 size"

似乎抛出了异常,但测试没有处理:

cannot be of size 0
Failures:
  1) cannot be of size 0
   Message:
     Error: Goal must be larger than 0 size
   Stacktrace:
     Error: Goal must be larger than 0 size
    at new Goal (/var/lib/stickshift/1d4f33cd01e442eaa154aed2e7697ca7/app-root/data/235917/prioritization/process.coffee:14:15)

有什么想法吗?

【问题讨论】:

  • 我也这么认为...所以我尝试在匿名函数中调用“new p.Goal("Goal 3", 0),如下所示:expect(f = do -> new p.Goal("Goal 3", 0)),但这也不起作用。
  • 原来这个语法有效:expect(-> new p.Goal("Goal 3", 0)).toThrow "Goal must be greater than 0 size"
  • 对,expect 想要执行一个函数,但 do 会在调用 expect 之前执行该函数。

标签: exception-handling coffeescript jasmine


【解决方案1】:

正如您已经发现的那样,您必须将对错误抛出代码的调用封装在一个匿名函数中。如果你不调用 expect 将得到你的错误代码的“结果”(如果有的话)。所以当期望被调用时,所有的“动作”都已经结束了。

【讨论】:

    猜你喜欢
    • 2012-06-14
    • 2016-06-16
    • 1970-01-01
    • 2019-11-18
    • 2012-11-15
    • 2011-11-22
    • 1970-01-01
    • 2011-12-20
    • 1970-01-01
    相关资源
    最近更新 更多