iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🔨

Stop Testing Every Single Function!

に公開

In short: Let's start unit testing from higher priority areas. Function-level unit testing often ends up being mere self-satisfaction.

Function-level Unit Tests are Low Priority

Function tests are easy to write, and it feels good to see test coverage increase. However, is it really beneficial to guarantee the behavior of functions like zerofill or milliSecToSec? Do they really need to be checked? I don't think so.

it('test zerofill', () => {
  expect(zerofill(3, 2)).toBe('03');
  expect(zerofill(42, 2)).toBe('42');
});

↑ Does it really benefit you to have this guaranteed?

Rather than at the function level, let's first test the application's specifications. That is the top priority. If the app is tested to work correctly, each function should naturally be tested as well.

Also, if the app's specifications change or the entire algorithm is replaced, there's a possibility that the function itself will no longer be used.

Anyway, let's test the app specifications first. Function-level tests are unnecessary until you have sufficient specification tests.

When to Write Function-Level Tests

Testing small functions doesn't provide much benefit, and the cost often outweighs the merit. However, you should still test corner cases and boundary values. Trying to verify every corner case of a function through application-level tests can actually be more troublesome. In those cases, it's better to just write a function-level test.

That being said, there aren't many functions that require corner case or boundary value testing. Therefore, most function-level tests should still be unnecessary.

Appendix: Concrete Examples of Specification Tests

it('can close modal with escape key', () => {
  const onClose = jest.fn();
  render(<Modal onClose={onClose}/>);
  fireEvent.keyDown(document.body, { code: 'Escape' });
  expect(onClose).toBeCalled();
});

↑ This is the kind of test I'm talking about. If this test passes, it guarantees that "the modal closes when an Escape key keydown event is fired on document.body."

Discussion