Class
class Work {
teams = [];
constructor(teams) {
this.teams = teams
this.teamAdded = this.teamAdded.bind(this)
}
teamAdded(team) {
this.teams = this.teams.concat(team)
return this.teams
}
}
Test
test('team is added on submission', async => {
var work = new Work()
var team = ['default team']
expect(work.teamAdded(team).toHaveLength(1)
})
For the sake of the error that I'm dealing with the class and test shown above contain all the info needed for my explanation. While writing tests to check the length of an array after data has been pushed to it, we ran into the following error
I understand that the property must be initialized with an empty array before attempting to perform array methods, but I do that above and still get the same error. I also make sure the function itself is properly bound to the class as well. Reading through the documentation, I know I don't have to spy on the function for checking the array length in vitest and attempting to mock array methods has led to brow furrowing results. Has anyone else run into this issue? Ive seen SO posts that have dealt with something similar in Jest, but I didn't see my specific situation of already initializing the property properly aleady when i searched around. All I would like to do is test that adding a team properly concatenates with the array and returns the length I expect.
You're not passing an array for teams into the constructor, and so even though you're initializing the property to an empty array in its definition, you're assigning undefined to it in the constructor.
concat
does not modify either array, but returns a new one, so you're missing an assignment.
class Work {
constructor(teams = [] /* Default value of empty array if not supplied */) {
this.teams = teams;
}
teamAdded(team) {
// Must assign the new array to the teams property
this.teams = this.teams.concat(team)
return this.teams
}
}
const work = new Work()
const team = ['default team']
work.teamAdded(team);
console.log(work.teams);