Ensure you have TypeScript installed globally using this command:
npm install -g typescript
This outlines how to setup a new TypeScript project with mocha support.
Create a new project folder. I will call mine ts-mocha-go
.
mkdir ts-mocha-go
cd ts-mocha-go
Then initialize your NodeJS project and initialize TypeScript.
npm init --y
tsc --init
Open the project in VSCode:
code .
Open the generated tsconfig.json
file and make these changes.
Change the outDir
where JavaScript files will be generated to ./dist
. The outDir
property is commented out by default.
It should look like this:
"outDir": "./dist",
Change your target language to ES6
"target": "es6",
Create a test
folder in your project root folder. In that folder create a file called test.ts
.
Copy this code into the file:
import assert from 'assert';
describe('My function', function() {
it('should test', function() {
assert.equal(1, 2);
});
});
If you open the test in VSCode you will see some errors.
TypeScript don't know what mocha is and it can't import the assert
node module.
To fix all of the above type errors install these dependencies:
npm install --save-dev mocha typescript ts-mocha
Ann install these TypeScript types:
npm install --save-dev @types/mocha
npm install --save-dev @types/node
Once you installed the above there should be no errors in your test.ts
file.
Add an entry to your package.json
file to configure your mocha test written in TypeScript to run using ts-mocha
"scripts": {
"test": "ts-mocha test/*.ts"
}
Run your mocha tests using:
npm test
You should have one failing test. Fix the it and run:
npm test
You should have one failing test.