gpt4 book ai didi

javascript - 当我的单元测试失败时回调被调用两次

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:35:32 25 4
gpt4 key购买 nike

我不明白为什么在我的 mocha 测试中我的保存回调在回调失败时被调用了两次。它不会两次调用保存,它只会再次触发保存的回调,但是当我的第二次单元测试失败时出现“应该”错误。如果我从第二次测试中取出失败的“应该”断言 should.exist err 它似乎工作正常并且不会触发保存索引回调两次。

class User

constructor : (@name, @email, @pwd) ->
save : (callback) ->
unless this.validate()
throw new Error('invalid data')
else
user =
name : @name
email : @email
pwd : @pwd

node = db.createNode user

node.save (err) ->
unless err
user.id = node.id;
node.index 'User', 'name', user.name.toLowerCase(), (err2) ->
#why is this being fired twice when an assert in the callback fail?
console.log '----------- triggering the save callback'
callback err2, user

else
callback err

Mocha 测试

describe "User", ->
it "should be able to save", (done) ->
user = new User("quark", "quark@ds9.com", "profit")
user.save (err, result) ->
should.exist result
done err

#this second unit test should fail since the duplicate checking is not yet implemented
it "should not allow duplicates to be saved", (done) ->
user = new User("quark", "quark@ds9.com", "profit")
user.save (err, result) ->
console.log err
should.exist err #this triggers the user.save callback to be fired twice
done null

测试结果

  User
◦ should be able to save: ----------- triggering the save callback
✓ should be able to save (43ms)
◦ should not allow duplicates to be saved: ----------- triggering the save callback
undefined
----------- triggering the save callback
{ name: 'AssertionError',
message: 'expected undefined to exist',
actual: undefined,
expected: undefined,
operator: undefined }
✓ should not allow duplicates to be saved


✔ 2 tests complete (69ms)

最佳答案

嗯,首先,具有预定义顺序的测试是糟糕的形式。您的第二个测试应该尝试将两个用户保存到数据库中,而不是依赖于第一个测试。

其次,我只能假设 db 在此上下文中是一个 node-neo4j Database 并且您的断言框架(should.js?chai?)正在使用异常.所以我的回答是基于这个假设。

看来node-neo4j是在异常情况下回调回调函数。

尝试只执行 throw 'blah' 而不是 should 断言,看看是否可以缩小范围。这没有在 node-neo4j 文档中列出,所以它看起来像是一个错误。

参见:http://coffeedoc.info/github/thingdom/node-neo4j/master/classes/Node.html#save-instance

关于javascript - 当我的单元测试失败时回调被调用两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12218842/

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