Fundamentos de TypeScript
¿Qué es TypeScript y por qué usarlo?
Instalación de Node.js y TypeScript CLI, configuración de tsconfig.json
Tipos primitivos: string, number, boolean, null, undefined de Typescript
Tipos especiales: any, unknown, never, void de TypeScript
Arrays, Tuplas, Enums en TypeScript
Funciones e Interfaces
Declaración de funciones, tipado de parámetros y valores de retorno
Parámetros opcionales, valores por defecto y sobrecarga de funciones
Creación y uso de interfaces de TypeScript
Propiedades opcionales, readonly, extensión de interfaces en TypeScript
Clases y Programación Orientada a Objetos
Creación de clases y constructores En TypeScript
Modificadores de acceso (public, private, protected) en Typescript
Uso de extends, sobreescritura de métodos en TypeScript
Introducción a Genéricos en Typescript
Restricciones con extends, genéricos en interfaces
Módulos y Proyectos
Importación y exportación de módulos en TypeScript
Agregando mi archivo de Typescript a un sitio web
Configuración de un proyecto Web con TypeScript
Selección de elementos, eventos, tipado en querySelector en TypeScript
Crear un proyecto de React.js con Typescript
Crea un proyecto con Angular y Typescript
Crea una API con Typescript y Express.js
Conceptos Avanzados
Introducción a types en TypeScript
Implementación de Decoradores de TypeScript
Async/await en Typescript
Pruebas unitarias con Jest y TypeScript
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
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.
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.
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.
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.
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.
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:
User
class we want to test.describe
to group our related testsUser
before each test with beforeEach
tests
that verify different aspects of the classTo 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
Jest has become one of the most popular testing tools in the JavaScript/TypeScript ecosystem for several reasons:
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
Want to see more contributions, questions and answers from the community?