
Setting up unit testing
This time we will will set up react testing library with jest to handle unit testing
Introduction
Automated testing is a must-have in every project. It helps make sure that the piece of code we wrote works as intended. I personally think that even simplest suite of tests with just a few of them is better than no testing at all. Maybe it takes some more, because we have to write those tests or update existing ones when we make changes to the component they are testing. I also had countless situations when unit tests saved me from pushing changes to code, which I accidentally broke in some edge cases. I simply forgot about them when I was implementing the changes and that happens. That's yet another good reason to have a decent set of automated tests. Today we are going to set up the testing environment and write tests for the code we wrote so far in Creating an articles service.
Installing necessary packages
Basically what we are going to do is to follow steps described in Next.js documentation. So we start by installing few packages we are going to use.
1yarn add -D jest jest-environment-jsdom @testing-library/react @testing-library/jest-dom @types/jest @ts-nodeAs you can see we are installing React Testing Library, which is a very popular UI elements testing library developed by React's team, and jest which is of most popular JavaScript testing library. We also install ts-node which is required by jest to read typescript config files.
Upgrading yarn to v4
To make our life easier and have access to commands like yarn create we are going to quickly jump from yarn in version 1.22 to the newest v4. To do so we run yarn init -2 in the terminal, and it should be all up and running. But look at the package.json file now. It is empty, because initializing newer version of yarn for some reason (at least at the time of writing this article), sets up a new package.json file. I used the GitHub tools in VS Code to see the diff of the package.json and I just copied back everything from the old file to the new one leaving only the lines which we didn't have before. After that run yarn to install all packages,
Configuration
Now when we have everything installed we need to create configuration files. We can actually use a command to initialize the jest config.
1yarn create jest@latestHere are the choices I made.
We are asked few questions and after that we have jest.config.ts. We need to update it with the configuration described in Next.js documentation.
1import type { Config } from 'jest';
2import nextJest from 'next/jest.js';
3const createJestConfig = nextJest({
4 // Provide the path to your Next.js app to load next.config.js and .env files in your test environment
5 dir: './',
6});
7// Add any custom config to be passed to Jest
8const config: Config = {
9 setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
10 coverageProvider: 'v8',
11 testEnvironment: 'jsdom',
12};
13// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
14export default createJestConfig(config);Furthermore, we need to create jest.setup.ts to add configuration for React Testing Library.
1import '@testing-library/jest-dom';And this is all we had to do to be ready to test run it. When we were initializing jest, there were new script added to our package.jsonn file yarn test which will run testing for us. So let's use this command and see what happens. We also want to add "test:watch": "jest -watch" which will keep the tests running on each file change to monitor the changes we are making.
Doesn't look impressive, because we don't have any tests to run yet. But we are about to change that. Before we do this, it is a good time to save what we have so far.
1git checkout -b setup-testing
2git add .
3git commit -m "feat: setup testing environment"Writing unit tests for the files we have so far
The convention we are going to follow is to name the tests files the same name the main file has, but we are going to add .test. at the end so for example MdArticleService.test.ts. We put test files in the same directory as the main file. But we will need some testing data first. We create few directories and files in lib/services as shown at the picture below.
Only the test.md file has content and all the rest are empty.
1---
2title: title
3description: description
4createdAt: 2000-01-01 00:00
5---
6# title
7contentWith this, we are good to go.
MdArticleService
We want to cover all the public functions in the service to make sure everything works as expected.
1import path from 'path';
2import { FileService } from '..';
3import { MdArticleService } from './MdArticleService';
4const testDataPath = path.join(__dirname, '../__testData__');
5const fileService = new FileService();
6const articleService = new MdArticleService(testDataPath, fileService);
7const testArticle = {
8 content: `
9# title
10content
11`,
12 title: 'title',
13 description: 'description',
14 slug: 'test',
15};
16it('should get all articles', async () => {
17 const articles = await articleService.getAll();
18 expect(articles).toHaveLength(5);
19 expect(articles.map((article) => article.slug).sort()).toEqual([
20 'dir1-file1',
21 'dir1-file2',
22 'dir2-file21',
23 'dir2-file22',
24 'test',
25 ]);
26 expect(articles[articles.length - 1]).toMatchObject(testArticle);
27});
28it('should get one article by slug', async () => {
29 const article = await articleService.getOneBySlug('test');
30 expect(article).toMatchObject(testArticle);
31});
32it('should throw error if article not found', async () => {
33 await expect(articleService.getOneBySlug('not-found')).rejects.toThrow(
34 'Article with slug "not-found" not found'
35 );
36});
37it('should get articles page', async () => {
38 const page = await articleService.getPage({ page: 1, limit: 2, firstPage: 1 });
39 const { hasNextPage, hasPreviousPage, items, pageCount } = page;
40 expect(hasNextPage).toBe(true);
41 expect(hasPreviousPage).toBe(false);
42 expect(items).toHaveLength(2);
43 expect(pageCount).toBe(3);
44});Here we have 4 tests which are testing all of our public functions we expose from MdArticleService class. They are pretty simple, and they are not the most sophisticated you can get but in our case I think they are good enough, to assure the most basic functionality of the service.
FileService
Next on our list is FileService. We are again using the same test files we have created. The same as before we want to have at least one test for each public methods.
1import path from 'path';
2import { FileService } from './FileService';
3const testDataPath = path.join(__dirname, '../__testData__');
4const fileService = new FileService();
5it('should get file and directory status', () => {
6 const file = fileService.getFileStats(testDataPath + '/test.md');
7 const directory = fileService.getFileStats(testDataPath);
8 expect(file).toHaveProperty('mtime');
9 expect(file).toHaveProperty('ctime');
10 expect(directory).toHaveProperty('mtime');
11 expect(directory).toHaveProperty('ctime');
12});
13it('should read file content', () => {
14 const fileContent = fileService.readFileContent(testDataPath + '/test.md');
15 expect(fileContent).toContain('title: title');
16});
17it('should build files tree', () => {
18 const filesTree = fileService.getTree(testDataPath);
19 expect(filesTree.length).toBe(3);
20 expect('directory' in filesTree[0]).toBe(true);
21 expect('directory' in filesTree[1]).toBe(true);
22 if ('directory' in filesTree[0]) {
23 expect(filesTree[0].directory.directoryName).toBe('dir1');
24 expect(filesTree[0].children.length).toBe(3);
25 }
26 if ('directory' in filesTree[1]) {
27 expect(filesTree[1].directory.directoryName).toBe('dir2');
28 expect(filesTree[1].children.length).toBe(2);
29 expect(filesTree[1].children[0]).toMatchObject({
30 relativePath: 'src/lib/services/__testData__/dir2/',
31 fileName: 'file21.md',
32 });
33 }
34});
35it('should check if file is a directory', () => {
36 let isDir = fileService.isDirectory({
37 directoryName: 'dir1',
38 absolutePath: testDataPath,
39 relativePath: '',
40 });
41 expect(isDir).toBe(true);
42 isDir = fileService.isDirectory({
43 fileName: 'file21.md',
44 absolutePath: '',
45 relativePath: '',
46 });
47 expect(isDir).toBe(false);
48});
49it('should check if file is a files tree', () => {
50 let isFilesTree = fileService.isFilesTree({
51 fileName: 'file21.md',
52 absolutePath: '',
53 relativePath: '',
54 });
55 expect(isFilesTree).toBe(false);
56 isFilesTree = fileService.isFilesTree({
57 directory: { absolutePath: '', directoryName: '', relativePath: '' },
58 children: [],
59 });
60 expect(isFilesTree).toBe(true);
61});
62it('should check if file is a file path', () => {
63 let isFilePath = fileService.isFilePath({
64 fileName: 'file21.md',
65 absolutePath: '',
66 relativePath: '',
67 });
68 expect(isFilePath).toBe(true);
69 isFilePath = fileService.isFilePath({
70 directory: { absolutePath: '', directoryName: '', relativePath: '' },
71 children: [],
72 });
73 expect(isFilePath).toBe(false);
74});So we have one test for each of the public methods.
StringService
Now the quick one as the class has just two methods to cover.
1import { StringService } from './StringService';
2it('should join array of strings', () => {
3 const joined = StringService.stringArrayToString(['one', 'two', 'three']);
4 expect(joined).toEqual('one two three');
5});
6it('should join array of strings with custom separator', () => {
7 const joined = StringService.stringArrayToString(['one', 'two', 'three'], ',');
8 expect(joined).toEqual('one,two,three');
9});
10it('should join array of strings with undefined values', () => {
11 const joined = StringService.stringArrayToString(['one', undefined, 'three']);
12 expect(joined).toEqual('one three');
13});
14it('should convert string to slug', () => {
15 const slug = StringService.stringToSlug('Some string with spaces');
16 expect(slug).toEqual('some-string-with-spaces');
17 const complexSlug = StringService.stringToSlug(
18 '!@#$%^&*()_+/|\\\\ -some string with spaces and and special 1234567890'
19 );
20 expect(complexSlug).toEqual('some-string-with-spaces-and-and-special-1234567890');
21});We wrote actually 3 separate tests for stringArrayToString because it has few use cases and I wanted to cover them all.
Running the tests and seeing the results
We can now once again use yarn test to run all of our test.
As you can see everything is working fine. I have been writing these test with yarn test:watch running, and it was checking all the changes as I went, and it was not passing from the start. Do not expect to write tests that are passing from the first trial. Actually it is a good practice to write first the test which fails to see if what we are checking would be caught by the test. I have seen a lot of test which were checking something, and they were always passing, but the reason was that they were not checking properly and whatever result the tested piece of code would return it will satisfy the test condition. Now we commit the changes, and again, please open new PR on GitHub and merge the changes back to master.
1git add .
2git commit -m "test: dd missing unit tests"Summary
So we are basically done with what we were about to do in the scope of this article. We are not going to write any tests for the page.tsx files, as I think the best will be to test the pages visible to the end users with the e2e testing which we will set up in a separate article as this is a whole new topic. But you might ask why do we need the React Testing Library for? It will be used to test the UI component we will be creating in the next parts of this series. I really encourage you to play with this, find your own way of setting things up, of how much tests you are going to write and how carefully you want to test each piece of your code. Please do not reject the idea of automated testing. It might seem like a waste of time, but hear me out - the time saved now will repay sooner or later with every new bug you will introduce to the code-base because of some piece of functionality broken after updating something else. At the beginning of a project, especially when you assume the project to be small and simple, this might not seem like a good place to add testing, but after few months of work you will thank yourself seeing failed tests caught something you were not aware of. And this is all for now. I want to invite you to the next part where we are going to start Creating Article component. It's time to make our blog look pretty.