— nodejs, typescript, yarn — 1 min read
- by Nick Grealy
Background:
Want to setup a typescript project from scratch, using the current best practices.
1npm init2echo 'console.log("hello world")' > index.ts3npm i -D typescript tslint ts-node nodemon dotenv dotenv-cli @types/node4./node_modules/.bin/tslint --init
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 }
1{2 "watch": ["src"],3 "ext": "ts,js,json",4 "ignore": ["src/**/*.spec.ts"],5 "exec": "ts-node ./src/index.ts"6}
Install dependencies (recommend nock
for external apis).
1npm i -D ts-mocha mocha chai jest @types/mocha sinon supertest
Setup test scripts.
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.
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 = null12
13 // before each test...14 beforeEach(() => {15 sinon.restore()16 // exampe stubbing17 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 // errors27
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})
TODO - complete