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

Should.js - determine equality between a single field in multiple object's against a single object

我正在测试 api 的美妙摩卡和 Should.js。

我执行 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。我似乎无法找到我想要的东西,或者也许应该以不同的方式处理。

假设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);

文档:

我可以这样建议:​​

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