A Pattern for testing instance variables in classes

A common struggle I have is testing logic in methods where there is lots of usage if instance variables, or methods internal to the class. It feels like there’s always a lot of boiler plate to getting the tests together. But it also feels like classes are best served when you can store a lot of data internal to the class and abstract that from the user.

A bit of a contrived example, that shows what I’m talking about is:

class PeopleCounter
constructor(people) {
this.people = people;
}
  count() {
return this.people.length;
}
}

var peeps = People.find();
var people = new PeopleCounter(peeps);
people.count();
> 4

In the above instance, testing is not as simple as running the count method, I have to be sure to load the data in through the constructor. While this example is straightforward, this becomes more difficult if the constructor is preparing the data before it enters the array.

I’ve known about this for a while, but I was just testing an app and thought I would play with some ideas. My first idea was:

class PeopleCounter
constructor(people) {
this.people = people;
}
  doCount(people) {
return people.length;
}
  count() {
return doCount(this.people);
}
}
var peeps = People.find();
var people = new PeopleCounter();
people.doCount(peeps);
> 4

I don’t like the idea of creating a second method for any other method using class methods. What I’m settling on for now is:

class PeopleCounter
constructor(people) {
this.people = people;
}
  count(people) {
var people = people || this.people;
return people.length;
}
}
var people = new PeopleCounter();
var peeps = People.find();
people.count(peeps);
> 4

While this pattern also involves some boilerplate in the function, it also helps to make the functions more immutable, since we’re immediately leaving the class variable behind.

How have you solved this problem?