Mocha-测试数组对象的值

时间:2018-11-07 16:45:25

标签: javascript mocha

如果我有一个像这样的数组:

[
{ "user": "tom",
  "email": "ee@co.com"
},
{ "user": "james",
  "email": "bb@co.com"
},
{ "user": "ryan",
  "email": "rr@co.com"
}
]

但是并不总是按此顺序返回-例如,如何检查ryan是否存在于这些对象之一中的某处?

3 个答案:

答案 0 :(得分:1)

如果您已经(或想要)使用lodash,那么我将使用其find

_.find(array, { user: "ryan" })

或者再添加几个字符,就可以做到:

array.find(elem => elem.user === "ryan")

如果找不到匹配的元素,则都返回undefined

答案 1 :(得分:0)

如果数组包含ryan,则函数返回true。

var input = [
{ "user": "tom",
  "email": "ee@co.com"
},
{ "user": "james",
  "email": "bb@co.com"
},
{ "user": "ryan",
  "email": "rr@co.com"
}
]
var output = input.some(function(eachRow){
    return eachRow.user === 'ryan';
});

console.log(output);

答案 2 :(得分:0)

我要解决的方法是将目标字段提取到数组中,然后检查值。

const chai = require('chai');
const expect = chai.expect;

describe('unit test', function() {
  it('runs test', function() {
    const users = [
      { "user": "tom",
        "email": "ee@co.com"
      },
      { "user": "james",
        "email": "bb@co.com"
      },
      { "user": "ryan",
        "email": "ryan@co.com"
      }
    ];
    const names = extractField(users, 'user'); // ['tom', 'james', 'ryan']   

    expect(names).to.include('ryan');
  });

  function extractField(users, fieldName) {
    return users.map(user => user[fieldName]);
  }
});

我正在使用chai进行断言。如果您想检查其他字段,我们只使用提取方法。

const emails = extractField(users, 'email');
expect(emails).to.include('ryan');

希望有帮助