Mat*_*hew 8 tdd mocha.js node.js coffeescript 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
Run Code Online (Sandbox Code Playgroud)
和一个名为的文件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."
Run Code Online (Sandbox Code Playgroud)
如果我在终端中运行这个命令:mocha -r should --compilers coffee:coffee-script -R spec
我有一个失败的测试(最后一个)说它期待一个异常"依赖任务'洗碗'没有完成." 但得到了"未定义".
如果我通过删除括号(-> task2.complete()).should.throw
来更改-> task2.complete().should.throw
,则测试通过,如果我不抛出异常则失败.但是,如果我将异常消息更改为随机的消息,它仍然会通过.难道我做错了什么?如果消息字面意思是"依赖任务'洗碗'没有完成,那么测试不应该通过."?
您正在抛出带有字符串的异常,而不是抛出错误对象。throw()
寻找后者。因此,如果您这样做,您的原始代码就可以工作:
throw new Error "Dependent task '#{@parent.name}' is not completed."
Run Code Online (Sandbox Code Playgroud)
如果您在 CoffeeScript 中编写的内容产生了毫无意义的结果,请尝试将其编译为 js (或将代码粘贴到try CoffeeScript中。您会看到:
-> task2.complete().should.throw "Dependent task 'wash dishes' is not completed."
Run Code Online (Sandbox Code Playgroud)
编译为:
(function() {
return task2.complete().should["throw"]("Dependent task 'wash dishes' is not completed.");
});
Run Code Online (Sandbox Code Playgroud)
它只是定义了一个函数,并不执行它。这就解释了为什么改变字符串没有什么区别。我希望这有帮助。
归档时间: |
|
查看次数: |
5507 次 |
最近记录: |