Mocha测试异步功能 [英] Mocha tests for asynchronous functions
问题描述
我正在编写一个节点包装程序,以便与外部api 进行交互,并且很难测试异步createJob
方法.下面是测试用例代码:
I'm writing a node wrapper to interact with an external api and am having a difficult time testing the asynchronous createJob
method. Below is the test case code:
api_key = "test_0dc8d51e0acffcb1880e0f19c79b2f5b0cc"
lob = require('../src/lob')(api_key)
should = require("should")
chai = require("chai")
data =
name: "test name"
to: "Bob"
from: "Alice"
object1: "foo"
object2: "bar"
describe "Job", ->
@timeout(50000)
describe "create", ->
it "should create a job with address_id", (done) ->
lob.jobs.createJob data, (new_job) ->
new_job.should.not.be.empty
new_job['name'].should.equal(data['name'])
done()
修改
上面的代码解决了这个问题
The above code resolves the issue
推荐答案
(coffeescript中的答案.如果要将咖啡转换为js,请使用
(Answer in coffeescript. If you'd like to convert coffee to js use http://coffeescript.org/, then the Try CoffeeScript tab.)
如果要测试异步代码,则需要使用done
模式:
If you're testing asynch code you'll need to use the done
pattern:
describe "User", ->
describe "#save()", ->
it "should save without error", (done) ->
user = new User("Luna")
user.save done
http://visionmedia.github.io/mocha/在异步代码"下.看起来createJob返回的是true,因为测试正在压缩代码以发送帖子等,然后说是的,我按照您的要求发送了所有内容!".
http://visionmedia.github.io/mocha/ under "Asynchronous code". Looks like createJob is returning true because the test is zipping through the code to send the post etc. and saying "yep, I sent all that stuff like you asked!".
我建议马丁·福勒(Martin Fowler)的有关使用Mocha测试异步js代码的文章: http://martinfowler. com/articles/asyncJS.html .
I'd recommend Martin Fowler's article on testing asynch js code with mocha: http://martinfowler.com/articles/asyncJS.html.
我有一大堆代码可以测试从数据库中检索用户(使用sinon进行存根).实际代码连接到数据库,然后使用用户的配置调用onSuccess:onSuccess(config)
I've got a chunk of code that tests retrieval of a user from the database (using sinon for stubbing). The real code connects to the db then calls the onSuccess with the user's configuration: onSuccess(config)
describe 'Config', ->
orgId = 'a'
errorHandler = ((msg) -> (throw msg))
beforeEach ->
readConfig = sinon.stub(sdl , 'getConfig')
readConfig.callsArgOnWithAsync(2, configSource, JSON.parse(jsonConfig))
afterEach ->
configSource.getConfig.restore()
...稍后
configSource.getConfig('520bc323de4b6f7845543288', errorHandler, (config) ->
config.should.not.be.null
config.should.have.property('preferences')
done()
)
这篇关于Mocha测试异步功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!