Javascript 使用vows、tobi和node.js进行RESTAPI测试
我正在尝试结合这些示例,为我的node.js/express应用程序编写一个誓言测试:Javascript 使用vows、tobi和node.js进行RESTAPI测试,javascript,node.js,express,vows,Javascript,Node.js,Express,Vows,我正在尝试结合这些示例,为我的node.js/express应用程序编写一个誓言测试: 创建新的用户对象 检查反应是否正常 使用返回的_id测试查找新创建的用户 再次使用_id测试更新用户 第1项和第2项工作正常,但我的子上下文“GET/users/:id”有问题。这是一个错误,我不知道为什么。我尝试过谷歌搜索和使用调试器,但我仍然看不到它是什么,我可能只是忽略了一些显而易见的东西 ···✗ Errored » 3 honored ∙ 1 errored 有人能告诉我为什么第四次誓言会出错吗
···✗ Errored » 3 honored ∙ 1 errored
有人能告诉我为什么第四次誓言会出错吗
这是我的誓言代码:
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)
}
你如何为第四次tes填充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)
据我所知,值是从父主题传递下来的?请看一下。我认为如果不调用此函数,它不会被传递。回调可能与此有关。回调,我将进一步调查,谢谢。“请注意,使用‘this.callback’的主题不能返回任何内容。同样,不返回任何内容的主题也必须使用‘this.callback’。”因此,托比似乎与誓言有些不相容。我在节点http.request周围做了一个简单的包装器,作为我的客户机。现在一切正常。这也有可能奏效,但我还没有试过。要不要分享一下你所做的修改!?