after several cycles of scrubbing out bugs and fine-tuning your spectacular app, youāre going to start realizing that youāre running into the same class of bugs and problems. or, maybe you know all the pitfalls of your code, but the other members of the your team donāt and inadvertently create bugs. regardless of the reason, a robust testing methodology baked into your coding will help provide a safety net for all the things that could go wrong as you add more and more code to the app.(if the act of debugging your code is removing problems, then the act of programming must be the act of adding them in, eh? š)
testing framework
Jest is built on top of the mature Jasmine project to be zero-configuration and much faster than its predecessor. itās built at Facebook so it also works really well with React which is the main recommendation of this guide as well.
getting setup
to create tests, you create .js files within folders named __tests__. alternatively, you can create files with a .test.js or .spec.js suffix. it comes bundled with create-next-app by default. if it isnāt installed you can do so via:
npm install--save-dev jest
how to write basic tests
the basic form of a test involves just asserting that something is true or not. for example:
it('sums numbers', () => {
Ā expect(sum(1, 2)).toEqual(3);
Ā expect(sum(2, 2)).toEqual(4);
});
testing components
to give you the ability to test React components, the Testing Library helps put simplify test writing.
coverage
to get a measurement on your code to see much your tests are actually examining your code, you can do the following:
npm test -- --coverage Ā # (note extra -- in the middle)
a widely-used product in this space that you can utilize is coveralls. i hear good things about codecov too but havenāt tested it yet.
debugging tests in Chrome
you can debug your tests via about:inspect URL in your Chrome browser. learn more on this technique here.
mentioned in CI section is the fact that you can setup a server so that you canādogfoodā your app before it goes out to the public. testing can catch a lot of things but sometimes new classes of errors can only crop up with real-world use.
tl;dr
intro
testing framework
getting setup
npm install --save-dev jest
how to write basic tests
it('sums numbers', () => {
Ā expect(sum(1, 2)).toEqual(3);
Ā expect(sum(2, 2)).toEqual(4);
});
testing components
coverage
npm test -- --coverage Ā # (note extra -- in the middle)
debugging tests in Chrome
playground
canary server