Programming Lessons

2024-09-17 - Classes and OOP

Setting up a typescript project

Basically, just adapt this package.json file, then type npm i:

{
  "name": "",
  "type": "module",
  "version": "1.0.0",
  "description": "",
  "scripts": {
    "build": "npm run build-code && npm run build-bundle",
    "build-code": "tsc",
    "build-bundle": "esbuild build/main.js --sourcemap --bundle --outfile=dist/main.cjs --platform=node --format=cjs",
    "run": "node dist/main.cjs",
    "br": "npm run build && npm run run",
    "test": "jest"
  },
  "author": "Erik Lee",
  "license": "MIT",
  "homepage": "",
  "devDependencies": {
    "@babel/preset-env": "^7.25.4",
    "@babel/preset-typescript": "^7.24.7",
    "@jest/globals": "^29.7.0",
    "@types/node": "^22.5.4",
    "esbuild": "^0.23.1",
    "jest": "^29.7.0",
    "typescript": "^5.6.2"
  },
  "dependencies": {
    "source-map-support": "^0.5.21"
  }
}

Unit testing with jest

jest is a javascript test framework that makes it easy to test small parts of your code. You have to install it along with babel:

npm i --save-dev @jest/globals
npm i --save-dev @babel/preset-env
npm i --save-dev @babel/preset-typescript

Here's how it works:

// first you have to import the functions you'll need
import {test,expect} from '@jest/globals';

// Now you make tests
// first call test("a description of your test", () => {a function that does the testing})

test("Make sure true things are still true", () => {
    // expect is a function that takes a value and returns a test object. The test
    // object has a ton of methods that check different things about the value, like
    // equality to other values, truthiness, definedness, etc. So you call expect on 
    // the value, then tell it how to check to see if it's what you wanted.
    expect(true===true).toBeTruthy();
})