laurent miller
laurent miller

Reputation: 21

Unit testing a function that i didn't write

So I have this function

const firstEntityValue = (entities: Object, entity: string) => {
  const val = entities && entities[entity] &&
    Array.isArray(entities[entity]) &&
    entities[entity].length > 0 &&
    entities[entity][0].value
  ;
  if (!val) {
    return null;
  }
  return typeof val === 'object' ? val.value : val;
};

I didn't write it, it was provided by the application I'm cloning. The app is working quite good, but now I'm Writing unit tests and I don't have any idea of the test to write to this function and even what to test. I already tested if the function was called once with the right parameters using mocha and sinon spy, but istanbul is telling me that all that comes after the declaration "const firstEntityValue" is not covered. Hope you can help me out.

Upvotes: 1

Views: 39

Answers (1)

Mik378
Mik378

Reputation: 22171

Unit testing is about testing behavior, not implementation

Testing only called arguments is clearly a bad practice because you would tie your tests to implementation details and your tests won't highlight what the code does. If you don't know what this code do, drop it, so that you will see what your app lacks.

This code could be tested as the following:

  • Should not return any value if matched entity has no values.
  • Should not return any value if the searched entity does not exist.
  • Should return the first entity value matching.

You could write some more tests to justify more statements of the function, but these main 3 statements are enough to figure out the practice.

Having no technical words in test labels is a pretty good thing.
You are now free to refactor the function code without altering tests; which is clearly the purpose of tests.

Upvotes: 1

Related Questions