【问题标题】:node.js mocha test requestnode.js mocha 测试请求
【发布时间】:2012-07-23 12:49:21
【问题描述】:

我正在使用 mocha.js 和 supertest.js 在 express.js 上测试我的 json 服务器的请求。这些是我的导入:

request = require('supertest')
assert  = require('assert')  # Node assert
app     = require('../app')  # Vanilla express app

这是我在快递应用中的请求实现:

app.get '/user/:id', (req, res) ->
  res.json {}

这是我的测试:

describe 'GET /user/:id', ->
  it 'should return the user data if user found', (done) ->
  request(app)
    .get("/user/some_id")
    .end((err, res) ->
      assert.equal('test', 'test')
      done()
    )

这可行,但如果我将请求更改为:

app.get '/user/:id', (req, res) ->
  User.findById req.param('id'), (err, doc) ->
    res.json {}

摩卡咖啡测试超时。我猜这与 find 是异步的并且测试不等待它完成这一事实有关。我该如何解决这个问题?

【问题讨论】:

    标签: node.js testing tdd express mocha.js


    【解决方案1】:

    尝试增加超时时间:

    mocha --timeout 5000
    

    默认值为 2000 毫秒,可能太短了。来自documentation

    【讨论】:

      【解决方案2】:

      切换到https://github.com/mikeal/request/ 解决了它。我现在在做

      这是我现在的测试:

      describe 'GET /user/:id', ->
        it 'should return the user data if user found', (done) ->
          request.get(
            'http://localhost:31000/user/500d365abb75e67d0c000006'  
            , (err, res, body) ->
              json = JSON.parse body
              assert.equal(res.statusCode, 200)
              assert.equal(json._id, '500d365abb75e67d0c000006')
              done()
          )
      

      现在一切都按预期进行,但我仍然想知道是否可以为此使用 supertest 或 vows。

      【讨论】:

        猜你喜欢
        • 2016-04-07
        • 1970-01-01
        • 2020-03-06
        • 1970-01-01
        • 2018-02-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多