node.js – Mocha,should.js和断言异常

我有一个文件app.coffee:

class TaskList

class Task
    constructor: (@name) ->
        @status = 'incomplete'
    complete: ->
        if @parent? and @parent.status isnt 'completed'
          throw "Dependent task '#{@parent.name}' is not completed."
        @status = 'complete'
        true
    dependsOn: (@parent) ->
        @parent.child = @
        @status = 'dependent'

# Prepare scope stuff
root = exports ? window
root.TaskList = TaskList
root.Task = Task

一个名为test / taskTest.coffee的文件

{TaskList,Task} = require '../app'
should = require 'should'

describe 'Task Instance',->
    task1 = task2 = null
    it 'should have a name',->
        something = 'asdf'
        something.should.equal 'asdf'
        task1 = new Task 'Feed the cat'
        task1.name.should.equal 'Feed the cat'
    it 'should be initially incomplete',->
        task1.status.should.equal 'incomplete'
    it 'should be able to be completed',->
        task1.complete().should.be.true
        task1.status.should.equal 'complete'
    it 'should be able to be dependent on another task',->
        task1 = new Task 'wash dishes'
        task2 = new Task 'dry dishes'
        task2.dependsOn task1
        task2.status.should.equal 'dependent'
        task2.parent.should.equal task1
        task1.child.should.equal task2
    it 'should refuse completion it is dependent on an uncompleted task',->
        (-> task2.complete()).should.throw "Dependent task 'wash dishes' is not completed."

如果我在终端中运行此命令:mocha -r should –compilers coffee:coffee-script -R spec我有一个失败的测试(最后一个)说它期待一个异常“依赖任务’洗碗’没有完成“.但得到了“未定义”.

如果我改变( – > task2.complete()).should.throw to – > task2.complete().should.throw删除括号,测试通过,如果我不抛出异常则失败.但是,如果我将异常消息更改为随机的消息,它仍然会通过.难道我做错了什么?如果消息字面意思是“依赖任务’洗碗’没有完成,那么测试不应该通过.”?

解决方法

您正在使用字符串抛出异常而不是抛出错误对象. throw()寻找后者.因此,如果您执行以下操作,原始代

throw new Error "Dependent task '#{@parent.name}' is not completed."

如果您在CoffeeScript中编写的内容产生的结果毫无意义,请尝试将其编译为js(或将代码粘贴到try CoffeeScript中.您将看到:

-> task2.complete().should.throw "Dependent task 'wash dishes' is not completed."

编译为:

(function() {
  return task2.complete().should["throw"]("Dependent task 'wash dishes' is not completed.");
});

它只是定义一个函数而不执行它.这解释了为什么更改字符串没有区别.我希望有所帮助.

相关文章

这篇文章主要介绍“基于nodejs的ssh2怎么实现自动化部署”的...
本文小编为大家详细介绍“nodejs怎么实现目录不存在自动创建...
这篇“如何把nodejs数据传到前端”文章的知识点大部分人都不...
本文小编为大家详细介绍“nodejs如何实现定时删除文件”,内...
这篇文章主要讲解了“nodejs安装模块卡住不动怎么解决”,文...
今天小编给大家分享一下如何检测nodejs有没有安装成功的相关...