Head start testing with Jest and Typescript

Head start testing with Jest and Typescript

Hello, this post is not super professional. It is a summary of notes that allow me to remember what I have to do or quickly explain to a friend how to start with Jest and Typescript.

It is part 1, so you will to learn basic stuff about Jest, configure, test a file, import code and use basic asserts.

Install dependencies for my project with Typescript and Jest

Hi, Dany or reader, you want to use Jest because it helps to write tests, is a runner, comes with a test cover, provides assertion, mocks more things.

  • We are going to create a calculator project directory.
  • Create package.json helps us define a test task for the future.
  • we install the typescript, Jest, test-jest packages, the jest types
  • Create two directories app and tests

If you want, you can copy and paste each line

dany@dany:~/Desktop$ mkdir calculator
dany@dany:~/Desktop$ cd calculator/
dany@dany:~/Desktop/calculator$ npm init --y
Wrote to /home/dany/Desktop/calculator/package.json:
 
{
  "name": "calculator",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}
dany@dany:~/Desktop/calculator$ npm install -save-dev typescript jest ts-jest @types/jest
 
+ jest@26.6.3
+ ts-jest@26.4.4
+ @types/jest@26.0.20
+ typescript@4.1.3
 
added 514 packages from 377 contributors and audited 515 packages in 16.711s
 
23 packages are looking for funding
  run `npm fund` for details
 
found 0 vulnerabilities

Create src directory and inside add app and test directory with his files Calculator.ts and Calculator.test.ts

dany@dany:~/Desktop/calculator$ mkdir src
dany@dany:~/Desktop/calculator$ cd src
dany@dany:~/Desktop/calculator$ mkdir app tests
dany@dany:~/Desktop/calculator$ cd app/
dany@dany:~/Desktop/calculator/app$ touch Calculator.ts
dany@dany:~/Desktop/calculator/app$ cd ..
dany@dany:~/Desktop/calculator$ cd tests/
dany@dany:~/Desktop/calculator/tests$ touch Calculator.test.ts

the touch command is only available in OSX and Linux. If you are using windows, please use

echo cal  > Calculator.ts

Use Describe and it functions.

Jest has two main functions Describe and it.

The Describe function allows for the creation of a suite or group tests, and the function expects a name of the group of tests as the first parameter and the callback function.

Its function allows us to define the test and where we will implement the logic for its validation.

Edit Calculator.test.ts and use Describe create a suite of tests related to Calculator and it to show a console.log-("jest is running").

Your code should look like:

describe("Calculator", () => {
 
   it("should print a jest is running", () => {
       console.log("jest is running")
   })
})

Edit the package.json and configure be run with npm test in the scripts area.

"main": "index.js",
  "scripts": {
    "test": "jest"
  },

If you use VSCode, you can install some extensions that allow you to run tests in the same IDE.

https://marketplace.visualstudio.com/items?itemName=Orta.vscode-jest

https://marketplace.visualstudio.com/items?itemName=firsttris.vscode-jest-runner

In our case, we run the test from the terminal.

> calculator@1.0.0 test /home/dany/Desktop/calculator
> jest
 
 PASS  tests/Calculator.test.ts
  Calculator
 should return a number (10 ms)
 
  console.log
    jest is running
 
      at Object.<anonymous> (tests/Calculator.test.ts:4:17)
 
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.655 s, estimated 1 s
Ran all test suites.

Stage 0 completed, we know which package install and use describe and it with Jest.

You can download a branch with the current state https://github.com/danywalls/jest_typescript_test_calculator/tree/setup-enviroment

Importing code to our test

We need to test our code in Jest, edit the Calculator.ts and create a class with the Increase method; it will increase a number to one.

export class Calculator {
   public static increase(value: number) {
       return value + 1;
   }
}

We are going to use the Increase function to get it. We need to do the following tasks in Calculator.test.ts

  • Import the Calculator into Calculator.test.ts
  • Create a new test with it for the Increase function.
  • In the Increase test, define an initialValue variable with 1
  • Use the Increase method from Calculator and Store the value in resultValue.
  • Print the resultValue (it should be 2).

Your code should look like:

import { Calculator } from "../app/Calculator";
 
describe("Calculator", () => {
 
    it("should return a number", () => {
        console.log("jest is running")
    })
 
    it("should increment the number", () => {
        const initValue = 1;
        const resultValue = Calculator.increase(initValue);
        console.log(resultValue);
    })
 })

Execute our tests using the npm run test, and we got the following error.

SyntaxError: Cannot use import statement outside a module
 
      at Runtime.createScriptFromCode (node_modules / jest-runtime / build / index.js: 1350: 14)
 
Test Suites: 1 failed, 1 total

It is because Jest needs to know where our typescript code is, and set it into jest.config.js

Create jes.confi.js in root path same level of package.json If you want to learn more about jest.config.js, the official website has a (https://jestjs.io/docs/en/configuration)[a lot of examples], here you can get an idea about some of them:

  • roots: the path from our archives.
  • transform: we say to use 'ts-jest'
  • testRegex: we tell Jest to look for spec files or test
  • moduleFileExtensions: the types of files we will support. Verbose: to show us results in the terminal.

Edit the jest.config.js and add the following settings

  • the path of our code src
module.exports = {
    roots: ['<rootDir>/src'],
    transform: {
        '^.+\\.tsx?$': 'ts-jest'
    },
    testRegex: '(/__test__/.*|(\\.|/)(test|spec))\\.[jt]sx?$',
    moduleFileExtensions: ['ts', 'js'],
    verbose: true
}

Rerun our tests and Jest knows where our files and our code read by Jest

dany@dany:~/Desktop/calculator/tests(import-code-and-configure)$ npm run test
 
> calculator@1.0.0 test /home/dany/Desktop/calculator
> jest
 
 PASS  src/tests/Calculator.test.ts
  Calculator
 should return a number (9 ms)
 should increment the number (1 ms)
 
  console.log
    jest is running
 
      at Object.<anonymous> (src/tests/Calculator.test.ts:7:17)
 
  console.log
    2
 
      at Object.<anonymous> (src/tests/Calculator.test.ts:13:17)
 
Test Suites: 1 passed, 1 total
Tests:       2 passed, two total
Snapshots:   0 total
Time:        1.76 s
Ran all test suites.

Stage 1 completed, we know how to configure Jest and call our code :)

Using expect and matchers

Expect is function to test a value. Jest provides a lot of "matcher" functions to assert values.

toBe and toEquals are two great matchers used for variables and objects.

Using toBe

The ToBe matcher validates primitive types such as strings, numbers, or boolean, let to use with our code.

Edit Calculator.test.ts and update the test to use the expect and toBe matcher functions.

  • Use expect to compare resultValue with Initial using toBe function.

The code will look like this:

it("should increment the number", () => {
       const initialValue = 1;
       const resultValue = Calculator.increase(initValue);
       expect(resultValue).toBe(initialValue + 1);
   })

Test, and it works! the expect function gets the restul value and compares the primitive value with the expected.

dany@dany:~/Desktop/calculator(import-code-and-configure)$ npm run test
> calculator@1.0.0 test /home/dany/Desktop/calculator
> Jest
 
 PASS  src/tests/Calculator.test.ts
  Calculator
 should return a number (11 ms)
 should increment the number (1 ms)
 
  console.log
    jest is running
 
      at Object.<anonymous> (src/tests/Calculator.test.ts:7:17)
 
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        0.791 s, estimated 2 s
Ran all test suites.
dany@dany:~/Desktop/calculator(import-code-and-configure)$

Using toEquals

First, create generateCalcSetting into Calculator.ts file, it returns an object with some properties from parameters values.

static generateCalcSetting(valueA: number, action: string, valueB: number) {
       let result : number;
       switch (action) {
           case "+":
               result = valueA + valueB;
               break;
           case "-":
               result = valueA - valueB;
               break;
           case "/":
               result = valueA / valueB;
           default:
               result = 0;
       }
      
 
       return  {
           valueA,
           mathAction: action,
           valueB,
           result
       }
   }

Create a new test for the generateCalcSetting method with the following.

  • Define an object with actualValues to be compared.
  • Store the result for generateCalcSetting into resultValue.
  • Use expect and toEqual to compare the returned object.

Your code will look like:

 it('should return a calculation Object logic', () => {
 
        const actualValue = {
            valueA: 1,
            mathAction: '+' ,
            valueB: 5,
            result: 6
        }
  
        const resultValue = Calculator.generateCalcSetting(1,'+',5);
        expect(actualValue).toEqual(resultValue);
    })

If you run your tests, everything works. We are matching handy objects.

Stage 3 completed!

Done

The short article helps to set up Jest, configure, import code, and use a basic matcher.

If you liked it, please share :)

The final stage of the project is in https://github.com/danywalls/jest_typescript_test_calculator/tree/master

Photo by National Cancer Institute on Unsplash

Real Software. Real Lessons.

I share the lessons I learned the hard way, so you can either avoid them or be ready when they happen.

User avatar
User avatar
User avatar
User avatar
+13K

Join 13,800+ developers and readers.

No spam ever. Unsubscribe at any time.

Discussion