A simple project to unit test typescript using jasmine. This project would help to getting started with setting up the unit test cases for typescript files.
Below are simple steps to get started. The set up can be done with just typescript and jasmine, however, we have used node and gulp to make it easier and maintainable as more files are added.
- Keep source typescript files in src folder
- Keep unit test cases spec files in tests folder
- npm commands are executed in command prompt set with directory root
- It is assumed that Node and TypeScript is already installed
Execute following to initialize package.json: npm init
Write simple function - Say Hello World in Hello.ts
- Add tsconfig.json file - configuration file for typescript
- Add gulp task to transpile typescript to javascript as below:
- If gulp is not installed - install using
npm install -g gulp-cli
npm install --save-dev typescript gulp gulp-typescript
- Add gulpfile.js and gulp taks to compile ts files. Watch task can be added to automatically compile ts files when changed
- If gulp is not installed - install using
npm install --save-dev jasmine-core
- Get jasmine typings for intellisense support:
npm install @types/jasmine
- Import module in source test file and write sample test for it using jasmine spec.
- Execute command:
gulp
orgulp watch
- to compile ts files - Run tests:
jasmine tests/*.spec.js
. This statement can be added in package.json and test cases can be run withnpm test
. Refer test under scripts in package.json.
We have set up to start writing unit test cases in typescript. Even if it seems that many steps are required, it is very simple.
The test cases would run in console. If we want to run in SpecRunner.html, one more step is required to bundle the modules so that they can be run in browser. e.g. Consume the source file module in test spec. The bundling can be done using Browserify, WebPack or any of your favourite module bundler.
The typescript documentation helped the lot in setting up this project.