使用vows,tobi和node.js进行REST API测试

时间:2011-08-02 21:14:34

标签: javascript node.js express vows

我正在尝试将示例herehere结合起来为我的node.js / express app写一个誓言测试:

  1. 创建新用户对象
  2. 检查反应是否合理
  3. 使用返回的_id测试查找新创建的用户
  4. 再次使用_id测试更新用户
  5. 第1项和第2项工作正常,但我的子上下文'GET / users /:id'有问题。它错了,我无法弄清楚为什么。尝试谷歌搜索并使用调试器,但我仍然无法看到它是什么,我可能只是忽略了一些明显的东西。

    ···✗ Errored » 3 honored ∙ 1 errored
    

    谁能告诉我为什么第4次发誓错误?

    这是我的誓言代码:

    var vows = require('vows')
      , assert = require('assert')
      , tobi = require('tobi')
    
    var suite = vows.describe('Users API')
      , now = new Date().getTime()
      , newUser = { name: now + '_test_user', email: now + '@test.com' }
      , browser = tobi.createBrowser(3000, 'localhost')
      , defaultHeaders = { 'Content-Type': 'application/json' }
    
    function assertStatus(code) {
      return function (res, $) {
        res.should.have.status(code)
      }
    }
    
    var client = {
      get: function(path) {
        return function() {
          browser.get(path, { headers: defaultHeaders }, this.callback)
        }
      },
      post: function(path, data) {
        return function() {
          browser.post(path, { body: JSON.stringify(data), headers: defaultHeaders }, this.callback)
        }
      }
    }
    
    suite.addBatch({
      'GET /users': {
        topic: client.get('/users'),
        'should respond with a 200 ok': assertStatus(200)
      },
      'POST /users': {
        topic: client.post('/users', newUser),
        'should respond with a 200 ok': assertStatus(200),
        'should return the new user': function(res, $){
          assert.isNotNull(res.body._id)
          assert.isNotNull(res.body.created_at)
          assert.isTrue(res.body._id.length > 0)
          assert.equal(newUser.name, res.body.name)
          assert.equal(newUser.email, res.body.email)
        },
        'GET /users/:id': {  // Sub-context of POST /users
          topic: function(res) { return client.get('/users/' + res.body._id) },
          'should respond with a 200 ok': assertStatus(200)
        }
      }
    })
    
    suite.export(module)
    

    修改

    我尝试按如下方式简化代码,以帮助查看this.callback是否存在问题,但错误仍然存​​在:

    'GET /users/:id': {  // Sub-context of POST /users
      topic: function(res) {
        console.log('About to request /users/' + res.body._id)
        browser.get('/users/' + res.body._id, { headers: defaultHeaders }, this.callback)
      },
      'should respond with a 200 ok': assertStatus(200)
    }
    

1 个答案:

答案 0 :(得分:1)

你如何为第四次测试填充res?它在行外不可见

'should return the new user'

尝试在addBatch调用之外创建id变量,并在第三次测试中设置它。然后打电话

client.get('/users/' + id)

修改

更好的是,在第三次测试中将其重新放入newUser:

'should return the new user': function(res, $){
  newUser.id = res.body._id
....

然后执行:

client.get('/users/' + newUser.id)