I had a discussion at work about whether to unit test a private static object we're using as data for a public component.
const data = {
45: { name: 'John' },
2: { name: 'Patricia' },
27: { name: 'Rei' },
}
The list goes on with dozens of items and in the real production example it has many more fields. In general, we shouldn't be testing something like this, it's just a private static object after all! The data is not modified by the component or by any function, it just serves as a static source of truth.
However, we have a data requirement that all names in the list must be unique, a requirement that could change in the future but an actual requirement nonetheless, and we know this requirement because of the nature of the data. Two items with the same name are considered an error in the data of this example.
So let's write a small unit test to make sure all names are unique, something like:
it('should have unique names', () => {
const dataset = new Set(Object.values(data).map(item => item.name))
expect(data).to.have.lengthOf(dataset.size)
})
A future maintainer or developer might work on this data in the future, adding or removing list items, and they might not know this requirement.
In this example the fact that names have to be unique is not evident unless you read the test, so this test is acting as documentation for the data, however imagine the real production example with much more data and fields, and more intricate relationships that are, however, easily testable.
I consider the test necessary while as my more senior colleague considered it unnecessary. Their points are quite valid:
- Only test features that you are exposing publicly.
- If someone modifies the data and make it wrong, that's their responsibility, not yours.
My points, I think, are also valid:
- Unless we force the structure via tests, there's no other way to make sure the data won't get messed up in the future.
- How wrong could it be having unit tests that are not testing a public feature but an internal structure?
What do you think and why? Any reference or link to a particular pattern would be appreciated. Thanks!
{ John: { id: 45}, Patricia: { id: 2} ...}
. That makes it obvious (and true) that the names are unique.street
,place
,avenue
,road
... you cannot have the typeavenue
twice, otherwise a component using that list will let you choose between the same values.