Should.js - 确定多个对象中的单个字段与单个对象之间的相等性

时间:2015-08-28 12:43:00

标签: javascript node.js mocha should.js

我正在用精彩的Mocha和Should.js测试api。

我执行GET并接收一组对象,例如:

[{
  username: 'boris',
  something: 123
},
{ 
  username: 'jeremy',
  something: 456
},
{ 
  username: 'steven',
  something: 789
},
{ ... },
{ ... },
{ ... }]

对于每个对象,我想确保用户名值与另一个对象中的属性匹配:

mockUsernames = {
    a  : 'bill',
    b  : 'ben',
    c  : 'boris'
};

你怎么能做到这一点?举个例子,我想要这样的东西:

.get()
...

  var someData = res.body;

  someData.forEach(function (e){
    e.username.should.equal(mockUsernames.a || mockUsernames.b || mockUsernames.c);
  });

...

正如预期的那样,这不能正常工作,因为should.equal使用相等的比较运算符。

任何推荐的should.js methods都会被v.appreciated。我似乎无法找到我想要的东西,或者也许这应该采用不同的方式。

2 个答案:

答案 0 :(得分:1)

假设mockUserNames(或其中包含的名称)也可以是数组,您有几个选择:

// Check one by one
someData.forEach(function(e) {
  mockUsernames.should.containEql(e.username);
});

// Check all in one go
mockUsernames.should.containDeep(someData.map(function(d) {
  return d.username;
}));

// If someData contains the same name multiple times, the previous method fails.
// Using `lodash` we can generate a list of unique names.
var _     = require('lodash');
var names = _.uniq(_.pluck(someData, 'username'));

mockUsernames.should.containDeep(names);

文档:

答案 1 :(得分:0)

我可以建议这样:

var should = require('should');

var res = [{
   username: 'boris',
   something: 123
 },
 { 
   username: 'jeremy',
   something: 456
 },
 { 
   username: 'steven',
   something: 789
}];

var mockUsernames = [ 'bill', 'ben', 'boris'];

res.should.matchEvery(function(it) { return mockUsernames.indexOf(it.username) >= 0 });
/* throws
AssertionError: expected Array [
  Object { something: 123, username: 'boris' },
  Object { something: 456, username: 'jeremy' },
  Object { something: 789, username: 'steven' }
] to match each Function { name: '' }
    expected Object { something: 456, username: 'jeremy' } to match Function { name: '' }
    at Assertion.fail (/Users/den/Projects/shouldjs/should.js/lib/assertion.js:180:17)
    at Assertion.prop.value (/Users/den/Projects/shouldjs/should.js/lib/assertion.js:65:17)
...
*/

mockUsernames = ['boris', 'steven', 'jeremy'];
res.should.matchEvery(function(it) { return mockUsernames.indexOf(it.username) >= 0 });//not throws