Fundamentos de TypeScript

1

¿Qué es TypeScript y por qué usarlo?

2

Instalación de Node.js y TypeScript CLI, configuración de tsconfig.json

3

Tipos primitivos: string, number, boolean, null, undefined de Typescript

4

Tipos especiales: any, unknown, never, void de TypeScript

5

Arrays, Tuplas, Enums en TypeScript

Funciones e Interfaces

6

Declaración de funciones, tipado de parámetros y valores de retorno

7

Parámetros opcionales, valores por defecto y sobrecarga de funciones

8

Creación y uso de interfaces de TypeScript

9

Propiedades opcionales, readonly, extensión de interfaces en TypeScript

Clases y Programación Orientada a Objetos

10

Creación de clases y constructores En TypeScript

11

Modificadores de acceso (public, private, protected) en Typescript

12

Uso de extends, sobreescritura de métodos en TypeScript

13

Introducción a Genéricos en Typescript

14

Restricciones con extends, genéricos en interfaces

Módulos y Proyectos

15

Importación y exportación de módulos en TypeScript

16

Agregando mi archivo de Typescript a un sitio web

17

Configuración de un proyecto Web con TypeScript

18

Selección de elementos, eventos, tipado en querySelector en TypeScript

19

Crear un proyecto de React.js con Typescript

20

Crea un proyecto con Angular y Typescript

21

Crea una API con Typescript y Express.js

Conceptos Avanzados

22

Introducción a types en TypeScript

23

Implementación de Decoradores de TypeScript

24

Async/await en Typescript

25

Pruebas unitarias con Jest y TypeScript

26

Principios SOLID, código limpio, patrones de diseño en Typescript

You don't have access to this class

Keep learning! Join and start boosting your career

Aprovecha el precio especial y haz tu profesión a prueba de IA

Antes: $249

Currency
$209
Suscríbete

Termina en:

0 Días
14 Hrs
46 Min
13 Seg
Curso de TypeScript

Curso de TypeScript

Amin Espinoza

Amin Espinoza

Pruebas unitarias con Jest y TypeScript

25/26
Resources

Unit testing is an essential component of professional software development, yet it is often overlooked or implemented superficially. In the TypeScript ecosystem, unit test integration is not only possible but surprisingly easy thanks to Jest, one of the most powerful testing tools available for JavaScript. Discover how to implement effective unit tests in your TypeScript projects and raise the quality of your code to a professional level.

How to set up Jest for TypeScript?

Before we start writing tests, we need to configure our environment so that Jest and TypeScript work together harmoniously. The process is fairly straightforward and requires the installation of a few specific packages.

To start, we need to install Jest along with the necessary types and the TypeScript-specific implementation:

npm install jest @types/jest ts-jest

These packages provide everything needed for Jest to interpret and run tests written in TypeScript. Once installed, we need to create some configuration files.

Configuring TypeScript for Jest

The first file we need to create is tsconfig.json, which contains the TypeScript configuration needed for interoperability with Jest:

{ " compilerOptions": { " target": "es5", " module": "commonjs", " strict": true, " esModuleInterop": true, " skipLibCheck": true, " forceConsistentCasingInFileNames": true }}

This configuration allows TypeScript and Jest to work together seamlessly, enabling features such as module import and ensuring consistency in file handling.

Jest Configuration

The next step is to create a jest.config.js file that tells Jest how it should handle TypeScript files:

module.exports = { preset: 'ts-jest', testEnvironment: 'node', transform: { '^. ts': 'ts-jest', }, moduleFileExtensions: ['ts', 'js', 'json'],};

This configuration sets ts-jest as the preset for transforming TypeScript files and defines the test environment as Node.js.

Updating package.json

We also need to modify our package.json to include the TypeScript dependency and configure the test script:

{ " name": "typescript-jest-example", " version": "1.0.0", " description": "Test example with Jest in TypeScript", " main": "index.js", " scripts": { " test": "jest" }, " dependencies": { " typescript": "^4.5.4" }, " devDependencies": { " @types/jest": "^27.0.3", " jest": "^27.4.5", " ts-jest": "^27.1.2" }}

With this configuration, we can run our tests simply with the npm test command.

How to write effective unit tests in TypeScript?

Once our environment is configured, we can start writing tests for our classes and functions. Let's take as an example a class User that we want to test:

// user.tsexport class User { private firstname: string; private lastname: string; private active: boolean;
 constructor(firstname: string, lastname: string, active: boolean = true) { this.firstname = firstname; this.lastName = lastName; this.active = active; }
 getName(): string { return this.firstName; }
 getProfile(): string { return `${this.firstName} ${this.lastName}`; }
 isStillActive(): boolean { return this.active; } }}

To test this class, we create a test file with the name user.test.ts:

// user.test.tsimport { User } from './user';
describe('User', () => { let user: User;
 beforeEach(() => { user = new User('John', 'John', 'Smith'); });
 test('must return the correct name', () => { expect(user.getName()).toBe('John'); });
 test('must return the correct profile', () => { expect(user.getProfile()).toBe('John Smith'); });
 test('must verify that the user is active', () => { expect(user.isStillActive()).toBeTruthy(); });
 test('must verify that user is inactive', () => { const userInactive = new User('Ana', 'Garcia', false); expect(userInactive.isStillActive()).toBeFalsy(); });});

In this test file:

  1. We import the User class we want to test.
  2. We use describe to group our related tests
  3. We create an instance of User before each test with beforeEach
  4. We define individual tests with tests that verify different aspects of the class

Running the tests

To run our tests, we simply use the command:

npm test

If everything is set up correctly, Jest will run all the tests and display the results in the terminal. A successful result would look like this:

PASS./user.test.ts User ✓ should return the correct name (3ms) ✓ should return the correct profile (1ms) ✓ should verify that the user is active ✓ should verify that the user is inactive (1ms)
Test Suites: 1 passed, 1 totalTests: 4 passed, 4 totalSnapshots: 0 totalTime: 2.5s

Why is Jest the best choice for TypeScript testing?

Jest has become one of the most popular testing tools in the JavaScript/TypeScript ecosystem for several reasons:

  • Ease of use: Configuration is minimal and the syntax is intuitive.
  • Performance: Jest runs tests in parallel, which makes it very fast.
  • Built-in functionality: Includes mocks, spies, timers and code coverage without the need for additional libraries.
  • Snapshots: Allows for easy UI testing
  • TypeScript support: Thanks to ts-jest, integration is seamless.

Jest's implementation with TypeScript is surprisingly simple compared to other testing tools in different programming languages. This ease of use does not sacrifice power or flexibility, making Jest an ideal choice for projects of any size.

Unit testing is an investment in the quality and maintainability of your code. With Jest and TypeScript, you have at your disposal a powerful combination that allows you to validate your code efficiently and reliably. Have you implemented unit tests in your TypeScript projects? Share your experience and the strategies you have found most effective.

Contributions 0

Questions 0

Sort by:

Want to see more contributions, questions and answers from the community?