Recently we recommended reading the checklist of 23 Node.js. security best practices that were collected from all top-ranked articles around the globe. And today we are sharing JS and Node testing best practices with you.
The testing code must stay dead-simple, with minimal dependencies, abstractions, and levels of indirection. One should look at a test and get the intent instantly. Most of the advice below are derivatives of this principle.
- A test report should tell whether the current application revision satisfies the requirements for the people who are not necessarily familiar with the code: the tester, the DevOps engineer who is deploying and the future you two years from now.
- Coding your tests in a declarative-style allows the reader to get the grab instantly without spending even a single brain-CPU cycle.
- A set of ESLint plugins were built specifically for inspecting the tests code patterns and discover issues.
- Testing the internals brings huge overhead for almost nothing.
- Test doubles are a necessary evil because they are coupled to the application internals, yet some provide immense value.
- Often production bugs are revealed under some very specific and surprising input — the more realistic the test input is, the greater the chances are to catch bugs early.
- Test many input combinations using Property-based testing.
Stay within the test: Minimize external helpers and abstractions.
- Going by the golden rule (bullet 0), each test should add and act on its own set of DB rows to prevent coupling and easily reason about the test flow.
- When trying to assert that some input triggers an error, it might look right to use try-catch-finally and assert that the catch clause was entered.
- Different tests must run on different scenarios: quick smoke, IO-less, tests should run when a developer saves or commits a file, full end-to-end tests usually run when a new pull request is submitted, etc.
More on best practices check here.
If you’re interested in integration testing, you should definitely read our post with the intro to integration testing.
And don’t miss our monthly most popular JS repositories!