Unit tests are very useful for checking how our app is working.
Otherwise, we run into all kinds of issues later on.
In this article, we’ll look at some best practices we should follow when writing JavaScript unit tests.
Tests as a Live Collaborative Document
Tests tell a lot about what our system does.
They have lots of descriptions and checks that show us what it can do.
There’re also things like Storybooks and UI components that tell us what they do.
We can look through each component with them.
Detect Visual Issues with Automated Tools
We can use various tools to detect visual issues.
They aren’t captured in unit or integration tests.
These tools save screenshots of our app so that we can see any flaws in our app.
There’re also tools like Applitools, Percy.io that let us manage the screenshots and detect visual noise with their own technology automatically.
Get Enough Coverage for Being Confident
We can get enough test coverage to make us confident in our tests.
Around 80% should cover the most important parts.
We can use CI tools to check if we meet the threshold for test coverage.
Most testing frameworks can get test coverage without much trouble.
Inspect Coverage Reports
We should check our test coverage reports to check what parts of our app hasn’t been covered by tests yet.
They can highlight the items in our code to check.
Just having the test coverage number doesn’t tell us which parts of our app are covered with tests.
Measure Logical Coverage
We can use mutation testing to tell which part of our app is actually tested rather than just visited.
To do that, we can intentionally change the values to check the outcomes as a result of them.
We may uncover cases that should fail that doesn’t come up that we may have not covered yet.
Preventing Test Code Issues
To check for issues with test code, we can use test linters to check for code.
There’re are plugins for ESLint like eslint-plugin-mocha or eslint-plugin-jest that’ll do these checks for us.
It’ll warn us when tests have no assertions for example.
Enrich Linters and Cancel Builds that have Linting Issues
If we have linting issues with our code, then we should stop them from being built since we want the linting issues to be fixed.
There’re many plugins for ESLint like the Airbnb and Standard.js plugins.
They can discover code issues and make sure the formatting is what everyone can agree on.
There’s also the eslint-plugin-security to check for security issues in our apps.
This will stop attackers from trying to attack our app.
Shorten the Feedback Loop
We can get feedback faster is we run CI locally on the developer’s machine.
They let us run our pipeline locally so that we can get useful testing insights.
So we can write our code, get feedback, and then make changes as needed.
Conclusion
We can enhance our testing workflows with CI tools and checking for things like visual defects.