Skip to content

Instantly share code, notes, and snippets.

@productiveme
Last active February 21, 2021 08:56
Show Gist options
  • Save productiveme/400437385228f0b7fd5417c8c257a7fa to your computer and use it in GitHub Desktop.
Save productiveme/400437385228f0b7fd5417c8c257a7fa to your computer and use it in GitHub Desktop.
Setup a new Typescript project in Visual Studio Code with jest for testing. Inspiration from https://medium.com/@RupaniChirag/writing-unit-tests-in-typescript-d4719b8a0a40

Developer setup

Initialize with Google Typescript Style (gts)

npx gts init
npm i
npm i -D jest ts-jest @types/jest

In package.json add the scripts for test and coverage:

  "scripts": {
    "test": "jest",
    "coverage": "jest --coverage",
    ...
  }

Add a jest.config.js file:

module.exports = {
  transform: {'^.+\\.ts?$': 'ts-jest'},
  testEnvironment: 'node',
  testRegex: '/tests/.*\\.(test|spec)?\\.(ts|tsx)$',
  moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node']
};

In .vscode/launch.json add configuration to debug tests:

    {
      "type": "node",
      "request": "launch",
      "name": "Jest Current File",
      "program": "${workspaceFolder}/node_modules/.bin/jest",
      "args": ["${relativeFile}"],
      "console": "integratedTerminal",
      "internalConsoleOptions": "neverOpen",
      "windows": {
        "program": "${workspaceFolder}/node_modules/jest/bin/jest"
      }
    }

Optional (but worth it)

Add the Jest Text Explorer extension.

Add Coverage badge Coverage

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment