TypeScript Unit Testing with Test Coverage
TypeScript Unit Testing with Test Coverage - The Startup - Medium
Photo by Fotis Fotopoulos on UnsplashI will describe the way to configure TypeScript unit testing with test coverage. I used TypeScript, Mocha, Chai and Istanbul for setting those up. I will guide you by creating a simple codes, belonging test codes and configurations that work altogether.Beware that these settings may or may not work if you are using different versions of packages. I used Node.js v10.16.0 for running this.Let’s start! 🚀You need create a directory, mkdir sample && cd sample andrun npm init -y on it.It will give you a package.json file like this.Now it is time to install the needed dependencies.npm install --save-dev typescript@3.5.3 chai@4.2.0 nyc@14.1.1 mocha@6.2.0 ts-node@8.3.0 cross-env@5.2.0 @types/chai @types/mocha @types/nodeWhat are all these packages? 😫Photo by chuttersnap on UnsplashTypeScript: Compiling TypeScript to JavaScriptChai: TDD/BDD style assertion libraryNyc (Istanbul): Test coverage libraryMocha: JavaScript testing frameworkTS-Node: TypeScript execution and REPL for Node.jsCross-env: Cross platform setting of environment scripts@types/node: TypeScript definition for Node.js@types/chai: TypeScript definition for Chai@types/mocha: TypeScript definition for MochaTypeScript Configuration ⚙️Create tsconfig.json in the root directory of the project folder, sample.sourceMap option is needed to be true to make Mocha to correctly picking up line numbers and also it helps Nyc to know the exact line numbers for test coverage as well.Write a Simple Code ✏️You will not need a complex code for testing out all these setups.Make one synchronous function and one asynchronous function for testing.Create src directory and write these functions in foo.ts .As you see, bar function always returns true and barAsync function always resolves true 2 seconds after it is called. I intentionally made the return false and resolve(false) to be never hit. In this way, you can test whether the test coverage is properly set up or not by seeing the uncovered lines of code.Write Some Tests 🧪Create test directory and write below tests in foo.test.ts.Let’s modify existing test script in package.json."test": "cross-env TS_NODE_FILES=true mocha — exit — require ts-node/register — colors test/**/*.ts"Now you can run npm test from your root directory and it will give you this.bar    √ sync function returns true    √ async function returns true (1002ms)2 passing (1s)Test Coverage 🔍So far, we wrote some codes and passing tests. It is time for setting up the test coverage.Write .nycrc in the root directory.nyc will read and use the configruation set in this file.Add "coverage": "nyc npm run test" in the "scripts" section in the package.json.So the final package.json file would be like this.Now you are ready to run the test coverage!Try running npm run coverage.bar    √ sync function returns true    √ async function returns true (1002ms)2 passing (1s)---------|-------|--------|-------|-------|-----------------|File     |% Stmts|% Branch|% Funcs|% Lines|Uncovered Line #s|---------|-------|--------|-------|-------|-----------------|All files|    80 |     50 |   100 |    80 |                 | foo.ts  |    80 |     50 |   100 |    80 |            5,15 |---------|-------|--------|-------|-------|-----------------|===================== Coverage summary =====================Statements   : 80% ( 8/10 )Branches     : 50% ( 2/4 )Functions    : 100%( 4/4 )Lines        : 80% ( 8/10 )============================================================You will see the result.Test Coverage Result 📃Go to the coverage directory and open up the index.html.Don’t be too suprised, the coverage and .nyc_output directory is auto-generated by nyc.All the run test files are shown here with test code coverageYou can click the detailed test coverage by clicking foo.ts .The green lines represents the test covered lines while the red lines shows the uncovered linesI went through the minimal guide for setting up TypeScript, Mocha, Chai and Istanbul. Depends on what you need, you may want to modify .nycrc, tsconfig.json and the test script defined in package.json.All of these codes are available in this repo.Thanks for reading this 😀