The Walrus
The Walrus

Reputation: 1208

How to test an array length of a react component?

Still getting tripped up on what and how to spy on stuff in React Components I've got this function, which basically filters a list and returns the matches when I type in a value for team:

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)
      ))
  }
}

And my test:

describe('other functions', () => {
  it('expects the matches array to have been filtered', () => {
    wrapper.instance().findMatchesForTeam('Chelsea');
    expect(matchesStub.length).to.equal(2);
  });
});

So I'm calling the method in my component and search for "Chelsea" and in the variable matchesStub I've got:

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"}
];

However my test says it should be length 3 (which is the initial length) and doesn't bother filtering. The code works, but the test doesn't.

Upvotes: 1

Views: 10328

Answers (1)

The Walrus
The Walrus

Reputation: 1208

Thanks to Will above, this solution worked:

expect(wrapper.instance().findMatchesForTeam('Chelsea').length).to.equal(2)

well, actually that is not entirely true. the final solution was:

const teamToFilterBy = {name: 'Chelsea'};
expect(wrapper.instance().findMatchesForTeam(teamToFilterBy).length).to.equal(2);

This was because my filter method above takes an object due to it requiring the name property. In my test I was only passing it a string and so even though it was logging it correctly, clearly a string can't have a .name attribute on it.

thanks to all who helped me get there!

Upvotes: 2

Related Questions