vitest testing in typescript

Unit testing is an important part of software development that ensures the quality of code. The testing process in Typescript is similar to Javascript. In fact, many of the popular testing libraries used in the JavaScript ecosystem can be used in Typescript project as well. One such library is Jest, which is a widely used JavaScript testing framework.

Here is how to set up Jest for Typescript in a project:

  1. Install the necessary packages:
npm install --save-dev jest @types/jest ts-jest
48 chars
2 lines
  1. Create a jest.config.js file at the root of your project, and add the following configuration to it:
index.tsx
module.exports = {
    preset: 'ts-jest',
    testEnvironment: 'node',
};
74 chars
5 lines
  1. Add the following scripts to your package.json file:
index.tsx
{
  "scripts": {
    "test": "jest"
  }
}
42 chars
6 lines
  1. Write your unit tests files in the __tests__ directory with a .test.ts extension. For example, example.test.ts.

  2. Run your tests using the npm test command.

Here is an example of a simple unit test using Jest:

index.ts
function add(a: number, b: number): number {
  return a + b;
}

describe('add function', () => {
  it('should return the sum of two numbers', () => {
    expect(add(1, 2)).toBe(3);
  });
});
191 chars
10 lines

This test checks whether the add function returns the sum of two numbers correctly or not.

To mock dependencies in your Typescript project, you can use jest.mock function. Here's an example:

index.ts
// person.ts
export class Person {
    constructor(private name: string, private age: number) {}

    public getInfo(): string {
        return `${this.name} is ${this.age} years old.`;
    }
}

// greet.ts
import { Person } from './person';

export function greet(person: Person): string {
    return `Hello, ${person.getInfo()}`;
}

// greet.test.ts
import { greet } from './greet';
import { Person } from './person'

jest.mock('./person', () => {
    return {
        Person: jest.fn().mockImplementation(() => {
            return {
                getInfo: jest.fn().mockReturnValue("mocked person info")
            }
        })
    }
});

describe("greet", () => {
    it("should return a greeting message", () => {
        const person = new Person("John", 30);
        const message = greet(person);
        expect(message).toEqual(`Hello, mocked person info`);
    });
});
883 chars
38 lines

This example shows how to mock the Person class using the jest.mock function.

gistlibby LogSnag