Javascript 如何测试react组件的数组长度?

Javascript 如何测试react组件的数组长度?,javascript,reactjs,testing,Javascript,Reactjs,Testing,仍然被什么以及如何监视React组件中的内容绊倒了 我有一个函数,它基本上过滤一个列表,并在我为团队键入值时返回匹配项: findMatchesForTeam = (team, venue) => { if (team) { console.log(team) // THIS GETS THE RIGHT TEAM (e.g. Chelsea) WHEN TESTING return this.props.matches.filter(t => t.homeTea

仍然被什么以及如何监视React组件中的内容绊倒了 我有一个函数,它基本上过滤一个列表,并在我为
团队
键入值时返回匹配项:

findMatchesForTeam = (team, venue) => {
  if (team) {
    console.log(team) // THIS GETS THE RIGHT TEAM (e.g. Chelsea) WHEN TESTING
    return this.props.matches.filter(t => t.homeTeam === team.name || t.awayTeam === team.name)
      .map((match) => (
        this.result(match)
      ))
  }
}
还有我的测试:

describe('other functions', () => {
  it('expects the matches array to have been filtered', () => {
    wrapper.instance().findMatchesForTeam('Chelsea');
    expect(matchesStub.length).to.equal(2);
  });
});
因此,我在我的组件中调用该方法并搜索“Chelsea”,在变量
matchesStub
中,我得到:

const matchesStub = [
  {awayGoals: 1, awayTeam: "Man City", homeGoals: 1, homeTeam: "Arsenal", month: "February"},
  {awayGoals: 2, awayTeam: "Man City", homeGoals: 3, homeTeam: "Chelsea", month: "February"},
  {awayGoals: 0, awayTeam: "Chelsea", homeGoals: 0, homeTeam: "Man Utd", month: "February"}
];

然而,我的测试表明它应该是长度3(这是初始长度),不需要过滤。代码有效,但测试无效。

多亏了上面的Will,这个解决方案成功了:

expect(wrapper.instance().findMatchesForTeam('Chelsea').length).to.equal(2)
事实上,这并不完全正确。最后的解决办法是:

const teamToFilterBy = {name: 'Chelsea'};
expect(wrapper.instance().findMatchesForTeam(teamToFilterBy).length).to.equal(2);
这是因为我上面的filter方法接受了一个对象,因为它需要name属性。在我的测试中,我只向它传递了一个字符串,因此即使它正确地记录了它,很明显,字符串上不能有
.name
属性


感谢所有帮助我到达那里的人

this.result(match)
做什么?您还应该记住,过滤器会创建新的数组。关于原始数组的断言没有意义。@YuryTarabanko result只返回一个4个跨度的div,其中包含匹配的详细信息,即目标和团队名称。您的函数返回过滤后的数组,但您没有检查返回结果。@Will ok sure,但如何在react组件中模拟和测试它?
expect(wrapper.instance().findMatchesForTeam('Chelsea')。长度)。至。相等(2)我怀疑会起作用。