gpt4 book ai didi

node.js - Mocha、should.js 和断言异常

转载 作者:搜寻专家 更新时间:2023-10-31 22:20:00 25 4
gpt4 key购买 nike

我有一个文件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 更改为 -> 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.");
});

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

关于node.js - Mocha、should.js 和断言异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12540948/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com