Skip to content
MountainPass Blog

Setting up a new Typescript project

nodejs, typescript, yarn1 min read

- by Nick Grealy

Background:

Want to setup a typescript project from scratch, using the current best practices.

Steps to deploy

1. Install Typescript in a new project

init.sh
1npm init
2echo 'console.log("hello world")' > index.ts
3npm i -D typescript tslint ts-node nodemon dotenv dotenv-cli @types/node
4./node_modules/.bin/tslint --init

2. Update start scripts

package.json
1"scripts": {
2 "build": "tsc --build",
3 "build:clean": "tsc --build --clean",
4 "start": "node dist/index.js",
5 "start:dev": "dotenv -e .env ts-node index.ts",
6 "start:watch": "dotenv -e .env nodemon index.ts",
7 }

3. Setup nodemon

nodemon.json
1{
2 "watch": ["src"],
3 "ext": "ts,js,json",
4 "ignore": ["src/**/*.spec.ts"],
5 "exec": "ts-node ./src/index.ts"
6}

4. Setup tests

Install dependencies (recommend nock for external apis).

runme.sh
1npm i -D ts-mocha mocha chai jest @types/mocha sinon supertest

Setup test scripts.

package.json
1"test": "ts-mocha --timeout 10000 --recursive './test/**/*.test.ts'",
2"test-watch": "nodemon --watch test --watch src --exec 'ts-mocha --timeout 10000 --recursive --bail' './test/**/*.test.ts'",
3"test-wip": "nodemon --watch test --watch src --exec 'ts-mocha --timeout 10000 --recursive --grep wip' './test/**/*.test.ts'",

An example test.

test/myfirsttest.test.ts
1const { expect } = require('chai')
2const { describe, it, beforeEach, afterEach } = require('mocha')
3const sinon = require('sinon')
4const request = require('supertest')
5const express = require('express')
6
7export { };
8
9describe.skip('SomeFeature', () => {
10 describe('SomeUserStory', () => {
11 let app = null
12
13 // before each test...
14 beforeEach(() => {
15 sinon.restore()
16 // exampe stubbing
17 sinon.stub(utils, 'writeConfigSync').returns({})
18 sinon.stub(ServiceRegistry.prototype, 'init').resolves()
19 })
20
21 // after each test...
22 afterEach(() => {
23 sinon.restore()
24 })
25
26 // errors
27
28 it('SomeUserScenario', async function () {
29 const response = await request(app).get('/status')
30 .expect('Content-Type', /json/)
31 .expect(401)
32 expect(response.body).to.eql({ message: 'Unauthorised - please provide a token.' })
33 sinon.assert.notCalled(ServiceRegistry.prototype.addService)
34 })
35
36 })
37})

5. Setup eslint

TODO - complete

© 2021 by MountainPass Blog. All rights reserved.
Theme by LekoArts