TypeScript Project Quickstart with test

1 minute read

Intro

Our engineering team at Browze, we have great activities related to tech.
workshop is one of them and has twice a week.

Usually, the workshop is lead by an engineer manager. He gives us a problem such as Bowling game, Mars Rover and Game of Life. We divide into two teams to solve this problem; discuss TDD, pair programming.

To build a solution program, quick setup skills give more time to discuss problems and code.

My colleague Luis shared his knowledge and I am writing it based on what he taught.

Practice

1. Install

ts-jest: To use Jest to test projects written in TypeScript.

yarn init -y
yarn add -D @types/jest jest typescript ts-jest

Creating ts-jest config

yarn ts-jest config:init

2. Add script

Add script test in package.json

  "scripts": {
    "test": "jest --watchAll"
  }

It will look like this.

{
  "name": "setup",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "devDependencies": {
    "@types/jest": "^26.0.24",
    "jest": "^27.0.6",
    "ts-jest": "^27.0.4",
    "typescript": "^4.3.5"
  },
  "scripts": {
    "test": "jest --watchAll"
  }
}

3. Create my first fake test

Create new file:teset.spec.ts in root Add first test

describe('my test', () => {
  it("works!", () => {
    expect(1).toBe(1);
  })
})

first-fake-test-file

4.Run test

run test command

yarn test

fake-test-result

5.Create `Account.ts` file

To check if test is working well with ts code in root.

  • Create new file Account.ts
  • export Account class
  • create works() method with return true
export class Account {
  works() {
    return true;
  }
}

6. Test `works()` method

Change test in test.spec.ts

expect(new Account().works()).toBe(true);

test.spec.ts should look like this.

import { Account } from './Account';

describe('my test', () => {
  it("works!", () => {
    expect(new Account().works()).toBe(true);
  })
})

7. Run

Create runthis.ts

import { Account } from './Account';

console.log(new Account().works());

ts-node: To execute TypeScript files or run TypeScript in a REPL environment.

yarn add -D ts-node

run

npx ts-node runthis.ts