向Chai / Mocha提供应包含的部分密钥列表
看来,如果我这样做
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
。 只要arrays中的3个键存在,我怎么能这样回来,尽pipe有更多的存在。 我不能总是预测每种情况下会发生什么。
更新:这是我如何要求柴, 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 )
如果你有这样一个对象(类似于你所描述的):
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"]);
即使您将值作为单独的parameter passing:
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
的风格正确:
var should = require('chai').should();
,你的问题可能只是你的body
对象或testing套件中的错字。
更新:在你添加更多关于你需要所有testing模块的信息后,应该指出几件事情:
-
首先,你需要两次
chai
,第二次build立时should
。 你做了:var chai = require( 'chai' ), should = require( 'chai' ).should(), ...
当你应该做的时候:
var chai = require( 'chai' ), should = chai.should(), ...
-
其次,如果您使用
chai-as-promised
,则应该按照本模块要求的方式声明body
键,如:Promise.resolve(body).should.eventually.include.keys([ "user", "title", "content" ]);
在请求处理程序中,最简单的解决scheme是不是:
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(); }