Using Linting, Formatting, and Unit Testing with Code Coverage to Enforce Quality Standards Licensed from Adobe Stock Photo If you are going to be writing code and shipping it to production, it’s important that the code is high quality. In , I showed you how to use docker-compose to leverage standardized, already existing Dockerfiles for development. The next step in getting our application ready for deployment is productionizing it. my last article I’m going to continue using the React/Parcel example from my earlier tutorial: Move over Next.js and Webpack! Here is the source code: https://github.com/patrickleet/streaming-ssr-react-styled-components I also haven’t done anything else related to getting the application “production ready”, so I’ll also talk about what is required for that, though it may take another article to finish… we’ll see how it goes. I’m ad-libbing this. Let’s start with some quality control. In this article we will explore Linting, Formatting, Unit Testing and Code Coverage and enforce some quality standards. Linting & Formatting According to Wikipedia, to “ , or a , is a tool that analyzes source code to flag programming errors, bugs, stylistic errors, and suspicious constructs.” Lint linter This means it enforces things like using spaces vs. tabs or making sure your code using semicolons consistently or not. There are probably a bunch of linting errors in my project currently. My goal so far has to demonstrate particular concepts and having too many sidebars about different things really takes away from the concepts at hand. Therefore I chose to forgo linting to keep the previous articles focused. Now that it’s time to “productionize” our app, quality is of increased priority. My preferred linter format is , which is a very minimalist setup. But before we set that up, let’s talk about formatting as well. StandardJS is similar to linting, but less focused on syntax errors and more focused on just making the code look prettier, hence the name of the popular package prettier. Formatting Thanks to a couple of awesome open-source contributors on Github we can use them both in one package — . Thanks to , , , and ! prettier-standard Adam Stankiewicz Kent C. Dodds Adam Garrett-Harris Benoit Averty In the past I’ve written about using husky to make sure rules are run before each commit. The prettier-standard package also recommends doing so, so let’s add prettier-standard, husky, and lint-staged now. Configuring prettier-standard First install the required packages: npm i --save-dev prettier-standard@ husky lint-staged 9.1 .1 In add the following “format” script and new “lint-staged” and “husky” sections: package.json { : { : }, : { : { : [ , ], : [ , ] } }, } //... "scripts" // ... "format" "prettier-standard 'app/**/*.js' 'app/**/*.jsx' 'server/**/*.js'" "lint-staged" "linters" "**/*.js" "prettier-standard" "git add" "**/*.jsx" "prettier-standard" "git add" // ... I couldn’t get RegExp to work so without looking into the source I’m assuming it uses glob and not RegExp. Now you can run to format your code and check for linting errors. Also, any time you try to commit, husky’s hook will be called, which will make sure any staged files ( stages files) are properly linted before allowing them to be commited. npm run format pre-commit git add Let’s see how I did on the first pass. ➜ npm run format > stream-all-the-things@ format /Users/patrick.scottgroup1001.com/dev/patrickleet/open-source-metarepo/stream-all-the-things > prettier-standard app/client.js ms app/imported.js ms app/styles.js ms app/App.jsx ms app/components/Header.jsx ms app/components/Page.jsx ms app/pages/About.jsx ms app/pages/ .jsx ms app/pages/Home.jsx ms app/pages/Loading.jsx ms server/index.js ms server/lib/client.js ms server/lib/ssr.js ms 1.0 .0 'app/**/*.js' 'app/**/*.jsx' 'server/**/*.js' 52 11 7 11 76 7 6 Error 5 6 6 8 11 17 And basically every file except had linting errors or didn’t look pretty enough! styles.js Ignoring files for linting and formatting There is one small issue which is specific to this project - is a generated file, and should be ignored by the linter. app/imported.js Although is has at the top of the file, prettier does not know to enforce linting rules. No worries, let’s undo changes to that file, and then create a file and an file to explicitly ignore it from being formatted on future runs. eslint-disabled .prettierignore .eslintignore git checkout -- ./app/imported.js Will undo changes to that file. And now create and with the following lines: .prettierignore .eslintignore app/imported.js dist coverage node_modules Now when running the file remains unchanged. Not addressing this could be problematic due to the fact the file is generated. npm run format app/imported.js Finally, I’ve mentioned committing should also as a run npm run format hook. Let’s try it out. pre-commit ➜ git commit -m husky > pre-commit (node v11 ) ↓ Stashing changes... [skipped] → No partially staged files found... ✔ Running linters... 'feat: prettier-standard' .6 .0 Here’s . the commit on Github Unit Testing and Code Coverage As part of productionizing our application, we really should make sure our code is well-tested. Ideally, you should do this along the way, but I’m a bad person and have neglected it in this project thus far. Let’s address that. Installing and Configuring Jest First, let’s install Jest for writing our unit tests. npm i --save-dev jest babel-jest Next, let’s add a jest config file so we configure jest to know where to find our files and be able to use pretty paths. Add the following file: jest.json { : [ ], : [ , ], : [ , ], : { : }, : [ ], : { : { : , : , : , : } }, : , : [ ] } "roots" "<rootDir>/__tests__/unit" "modulePaths" "<rootDir>" "/node_modules/" "moduleFileExtensions" "js" "jsx" "transform" "^.+\\.jsx?$" "babel-jest" "transformIgnorePatterns" "/node_modules/" "coverageThreshold" "global" "branches" 10 "functions" 10 "lines" 10 "statements" 10 "collectCoverage" true "collectCoverageFrom" "**/*.{js,jsx}" Alright, let’s unpack that. First, we set to . I like putting staging tests in so setting the root to will allow me to do that later on. roots <rootDir>/__tests__/unit __tests__/staging __tests__/unit Next, we set to the root directory, and . This way in our tests instead of using relative paths like we can just import or . modulePaths node_modules ../../ app/* server/* The next two keys are telling jest to use babel to load our files so things like will work without issues. import And finally, the last three sections define coverage settings — the minimum thresholds, all at 10%, and where to collect coverage from. In this article I just aim to get the pieces configured. In the next one I’ll increase the coverage threshold to 100% and walk through that process of getting there. And to run, we can define a script in our 's scripts section. Because we are using babel-jest we will need to provide some babel settings as well, so we can set to , and we will address that in the next section. test package.json BABEL_ENV test : { : , : } "scripts" // ... "test" "cross-env BABEL_ENV=test jest --config jest.json" "test:watch" "cross-env BABEL_ENV=test jest --config jest.json --watch" Configuring Jest with Babel First in order for the tests to work, we are going to need configure some babel settings. Add the following section in the env key of your .babelrc file: { : { : { :[ [ ], [ ], ], : [ [ ] ] }, } } "env" "test" "presets" "@babel/preset-env" "@babel/preset-react" "plugins" "@babel/plugin-syntax-dynamic-import" // ... And let’s install the plugins and presets that we’ve referenced: npm i --save-dev @babel/core @babel/preset-env @babel/preset-react @babel/plugin-syntax-dynamic- babel-jest import We have 0% coverage currently, let’s add one test for the app, and one test for the server which should put us above our low threshold of 10%. Testing the client side app with Enzyme First, let’s test a file in app. We will want to shallow-render our components in app to test them. To do so, we will use . enzyme npm i --save-dev enzyme enzyme-adapter-react -16 Enzyme has a setup step that we must add before we can use it in our tests. In our file, add a new key: jest.json { : } //other settings "setupTestFrameworkScriptFile" "<rootDir>/__tests__/setup.js" And the setup file at : __tests__/unit/setup.js { configure } ; Adapter ; configure({ : Adapter() }); import from 'enzyme' import from 'enzyme-adapter-react-16' adapter new Now with Enzyme configured we can create : __tests__/unit/app/pages/Home.jsx Seems how our component is just a single function, that’s all we need to reach 100% coverage for this file. Server side tests React { shallow } Home describe( , () => { it( , () => { expect(Home).toBeDefined() tree = shallow( import from 'react' import from 'enzyme' import from 'app/pages/Home.jsx' 'app/pages/Home.jsx' 'renders style component' const ) expect(tree.find('Page')).toBeDefined() expect(tree.find('Helmet').find('title').text()).toEqual('Home Page') expect(tree.find('div').text()).toEqual('Follow me at @patrickleet') expect(tree.find('div').find('a').text()).toEqual('@patrickleet') }) }) < /> Home I want to test but before I do, there are a couple of refactors that will make our lives a little bit easier. server/index.js Unit tests are meant to test a single unit. That means even though our app is using express, we are not testing express as part of this unit test. We are testing that our server is configured with the appropriate routes, middleware, and that listen is called to start the server. Unit Tests for express belong in the express project. In order to only test the single unit we care about, we can use mocking to create lightweight interfaces that we can track using jest.mock. If we extract the server instantiation out of index into it’s own file, we will be able to more easily mock the server. Create the file with the following contents: server/lib/server.js express server = express() serveStatic = express.static import from 'express' export const export const And update server/index.js like so: path log { server, serveStatic } ssr server.use( , serveStatic(path.resolve(process.cwd(), , )) ) server.get( , ssr) port = process.env.PORT || server.listen(port, () => { log.info( ) }) import from 'path' import from 'llog' import from './lib/server' import from './lib/ssr' // Expose the public directory as /dist and point to the browser version '/dist/client' 'dist' 'client' // Anything unresolved is serving the application and let // react-router do the routing! '/*' // Check for PORT environment variable, otherwise fallback on Parcel default port const 1234 `Listening on port ...` ${port} Now in our test we can simply mock instead of a more complex mock of express. server/lib/server.js Let’s create the test at : __tests__/unit/server/index.js jest.mock( ) jest.mock( , () => ({ : { : jest.fn(), : jest.fn(), : jest.fn() }, : jest.fn( ) })) jest.mock( ) describe( , () => { it( , () => { { server, serveStatic } = ( ) expect(server.use).toBeCalledWith( , ) expect(serveStatic).toBeCalledWith( ) expect(server.get).toBeCalledWith( , expect.any( )) expect(server.listen).toBeCalledWith( , expect.any( )) }) }) import 'server/index' 'llog' 'server/lib/server' server use get listen serveStatic => () "static/path" 'server/lib/ssr' 'server/index.js' 'main' const require 'server/lib/server' '/dist/client' "static/path" ` /dist/client` ${process.cwd()} '/*' Function 1234 Function If we run the coverage now, we will notice that the coverage for is not 100%. We have an anonymous function passed to listen which is difficult to get at. This calls for some minor refactoring. server/index.js Refactor the listen call to extract the anonymous function. onListen = () => { log.info( ) } server.listen(port, onListen(port)) export const => port `Listening on port ...` ${port} Now we can easily test . onListen Let’s add another test to our suite to account for it. server/index.js { onListen } describe( , () => { it( , () => { log = ( ) onListen( )() expect(log.info).toBeCalledWith( ) }) }) import from 'server/index' // ... 'server/index.js' // ... 'onListen' const require 'llog' 4000 'Listening on port 4000...' And with that, we have 100% coverage for as well as . server/index.js app/pages/Home.jsx With our two tests we’ve managed to increase our coverage from 0% to 35–60% depending on the metric: Current Coverage Add testing to pre-commit hooks Lastly, we want to only make sure that tests as a pre-commit hook as well to prevent broken tests from making it into the code, and later on, any untested code. In change to: package.json pre-commit : "pre-commit" "lint-staged && npm run test" Now when someone tries to commit to the project it will enforce the coverage standards defined in your Jest config as well as making sure all the tests pass! Conclusion When it comes time to get your application production ready, it is imperative to enforce quality standards in an automated way. In this article I showed you how to set up and configure tools for linting and formatting your code, as well as how to configure your project for testing using enzyme and jest with enforced code coverage. In the next part we will increase coverage to 100% before continuing on with creating a production ready Dockerfile. As always, if you’ve found this helpful, please click and hold the clap button for up to 50 claps, follow me, and share with others! Best, Patrick Lee Scott Check out the other articles in this series! This was part 3. Part 1: Move over Next.js and Webpack Part 2: A Better Way to Develop Node.js with Docker Part 4: The 100% Code Coverage Myth Part 5: A Tale of Two (Docker Multi-Stage Build) Layers