似乎我做了
describe( 'Add Youtube', function () {
it( 'should return the video data, including user, title and content fields', function ( done ) {
this.timeout( 5000 )
request({
method: 'POST',
url: 'https://localhost:8443/api/add',
json: true,
strictSSL: false,
body: {
"type": "youtube",
"url": "https://www.youtube.com/watch?v=uxfRLNiSikM"
},
headers: {
"Authorization": "Bearer " + newTestUser.token
} }, function ( err, response, body ) {
body.should.include.keys( [ "user", "title", "content" ] )
done()
})
})
})
这会返回错误,因为回来的对象也有密钥message
。只要数组中的3个键存在,我怎么能让它返回传递,尽管还有更多。我无法预测每种情况下的情况。
更新:以下是我要求Chai和should
的方式。
var chai = require( 'chai' ),
chaiAsPromised = require( 'chai-as-promised' ),
should = require( 'chai' ).should(),
path = require( 'path' ),
getUser = require( '../helpers/get-user' ),
userController = require( '../controllers/userController' ),
blogController = require( '../controllers/blogController' ),
request = require( 'request' ),
User = require( '../models/userModel' ),
Content = require( '../models/contentModel' ),
shortid = require( 'shortid' )
chai.use( chaiAsPromised )
答案 0 :(得分:2)
如果您有像这样的对象(类似于您所描述的):
var obj= {
user: "user",
title: "title",
content: "content",
message: "message"
};
以下所有断言都应该通过:
obj.should.include.keys(["user", "title", "content"]);
obj.should.includes.keys(["user", "title", "content"]);
obj.should.contain.keys(["user", "title", "content"]);
obj.should.includes.keys(["user", "title", "content"]);
即使您将值作为单独的参数传递:
obj.should.include.keys("user", "title", "content");
obj.should.includes.keys("user", "title", "content");
obj.should.contain.keys("user", "title", "content");
obj.should.includes.keys("user", "title", "content");
因此,假设您正确地需要chai
' should
样式:
var should = require('chai').should();
,您的问题可能只是body
对象或测试套件中的错字。
更新:在您添加了有关所有测试模块所需方式的更多信息后,应指出以下几点:
首先,您需要chai
两次,第二次需要设置should
。你做了:
var chai = require( 'chai' ),
should = require( 'chai' ).should(),
...
你应该完成的时间:
var chai = require( 'chai' ),
should = chai.should(),
...
其次,如果您正在使用chai-as-promised
,则应该设置body
个密钥the way this module requires,例如:
Promise.resolve(body).should.eventually.include.keys([ "user", "title", "content" ]);
答案 1 :(得分:1)
在您的请求处理程序中,最简单的解决方案是:
function ( err, response, body ) {
var expected={},
expected_keys=['user','title','content'];
expected_keys.forEach(function(key){
expected[key]=body[key];
});
expected.should.include.keys(expected_keys);
done();
}
或者使用我最喜欢的工具lodash:
var _=require('lodash');
function ( err, response, body ) {
var expected_keys=['user','title','content'];
_.pick(body,expected_keys).should.include.keys(expected_keys);
done();
}