diff --git a/adev-es/src/app/routing/sub-navigation-data.ts b/adev-es/src/app/routing/sub-navigation-data.ts index 9fe4a39..b7488a8 100644 --- a/adev-es/src/app/routing/sub-navigation-data.ts +++ b/adev-es/src/app/routing/sub-navigation-data.ts @@ -602,12 +602,12 @@ const DOCS_SUB_NAVIGATION_DATA: NavigationItem[] = [ contentPath: 'guide/testing/code-coverage', }, { - label: 'Testing utility APIs', + label: 'APIs utilitarias de pruebas', path: 'guide/testing/utility-apis', contentPath: 'guide/testing/utility-apis', }, { - label: 'Zone.js Testing Utilities', + label: 'Utilidades de pruebas de Zone.js', path: 'guide/testing/zone-js-testing-utilities', contentPath: 'guide/testing/zone-js-testing-utilities', }, @@ -632,12 +632,12 @@ const DOCS_SUB_NAVIGATION_DATA: NavigationItem[] = [ contentPath: 'guide/testing/component-harnesses-testing-environments', }, { - label: 'Migrating from Karma to Vitest', + label: 'Migrando de Karma a Vitest', path: 'guide/testing/migrating-to-vitest', contentPath: 'guide/testing/migrating-to-vitest', }, { - label: 'Testing with Karma and Jasmine', + label: 'Pruebas con Karma y Jasmine', path: 'guide/testing/karma', contentPath: 'guide/testing/karma', }, diff --git a/adev-es/src/content/guide/testing/karma.en.md b/adev-es/src/content/guide/testing/karma.en.md new file mode 100644 index 0000000..d5d59cf --- /dev/null +++ b/adev-es/src/content/guide/testing/karma.en.md @@ -0,0 +1,199 @@ +# Testing with Karma and Jasmine + +While [Vitest](https://vitest.dev) is the default test runner for new Angular projects, [Karma](https://karma-runner.github.io) is still a supported and widely used test runner. This guide provides instructions for testing your Angular application using the Karma test runner with the [Jasmine](https://jasmine.github.io) testing framework. + +## Setting Up Karma and Jasmine + +You can set up Karma and Jasmine for a new project or add it to an existing one. + +### For New Projects + +To create a new project with Karma and Jasmine pre-configured, run the `ng new` command with the `--test-runner=karma` option: + +```shell +ng new my-karma-app --test-runner=karma +``` + +### For Existing Projects + +To add Karma and Jasmine to an existing project, follow these steps: + +1. **Install the necessary packages:** + + + + npm install --save-dev karma karma-chrome-launcher karma-coverage karma-jasmine karma-jasmine-html-reporter jasmine-core @types/jasmine + + + yarn add --dev karma karma-chrome-launcher karma-coverage karma-jasmine karma-jasmine-html-reporter jasmine-core @types/jasmine + + + pnpm add -D karma karma-chrome-launcher karma-coverage karma-jasmine karma-jasmine-html-reporter jasmine-core @types/jasmine + + + bun add --dev karma karma-chrome-launcher karma-coverage karma-jasmine karma-jasmine-html-reporter jasmine-core @types/jasmine + + + +2. **Configure the test runner in `angular.json`:** + + In your `angular.json` file, find the `test` target and set the `runner` option to `karma`: + + ```json + { + // ... + "projects": { + "your-project-name": { + // ... + "architect": { + "test": { + "builder": "@angular/build:unit-test", + "options": { + "runner": "karma", + // ... other options + } + } + } + } + } + } + ``` + +3. **Update `tsconfig.spec.json` for Jasmine types:** + + To ensure TypeScript recognizes global testing functions like `describe` and `it`, add `"jasmine"` to the `types` array in your `tsconfig.spec.json`: + + ```json + { + // ... + "compilerOptions": { + // ... + "types": [ + "jasmine" + ] + }, + // ... + } + ``` + +## Running Tests + +Once your project is configured, run the tests using the [`ng test`](cli/test) command: + +```shell +ng test +``` + +The `ng test` command builds the application in _watch mode_ and launches the [Karma test runner](https://karma-runner.github.io). + +The console output looks like below: + +```shell + +02 11 2022 09:08:28.605:INFO [karma-server]: Karma v6.4.1 server started at http://localhost:9876/ +02 11 2022 09:08:28.607:INFO [launcher]: Launching browsers Chrome with concurrency unlimited +02 11 2022 09:08:28.620:INFO [launcher]: Starting browser Chrome +02 11 2022 09:08:31.312:INFO [Chrome]: Connected on socket -LaEYvD2R7MdcS0-AAAB with id 31534482 +Chrome: Executed 3 of 3 SUCCESS (0.193 secs / 0.172 secs) +TOTAL: 3 SUCCESS + +``` + +The test output is displayed in the browser using [Karma Jasmine HTML Reporter](https://github.com/dfederm/karma-jasmine-html-reporter). + +Jasmine HTML Reporter in the browser + +Click on a test row to re-run just that test or click on a description to re-run the tests in the selected test group ("test suite"). + +Meanwhile, the `ng test` command is watching for changes. To see this in action, make a small change to a source file and save. The tests run again, the browser refreshes, and the new test results appear. + +## Configuration + +The Angular CLI takes care of Jasmine and Karma configuration for you. It constructs the full configuration in memory, based on options specified in the `angular.json` file. + +### Customizing Karma Configuration + +If you want to customize Karma, you can create a `karma.conf.js` by running the following command: + +```shell +ng generate config karma +``` + +HELPFUL: Read more about Karma configuration in the [Karma configuration guide](http://karma-runner.github.io/6.4/config/configuration-file.html). + +### Setting the Test Runner in `angular.json` + +To explicitly set Karma as the test runner for your project, locate the `test` target in your `angular.json` file and set the `runner` option to `karma`: + +```json +{ + // ... + "projects": { + "your-project-name": { + // ... + "architect": { + "test": { + "builder": "@angular/build:unit-test", + "options": { + "runner": "karma", + // ... other options + } + } + } + } + } +} +``` + +## Code coverage enforcement + +To enforce a minimum code coverage level, you can use the `check` property in the `coverageReporter` section of your `karma.conf.js` file. + +For example, to require a minimum of 80% coverage: + +```javascript +coverageReporter: { + dir: require('path').join(__dirname, './coverage/'), + subdir: '.', + reporters: [ + { type: 'html' }, + { type: 'text-summary' } + ], + check: { + global: { + statements: 80, + branches: 80, + functions: 80, + lines: 80 + } + } +} +``` + +This will cause the test run to fail if the specified coverage thresholds are not met. + +## Testing in continuous integration + +To run your Karma tests in a CI environment, use the following command: + +```shell +ng test --no-watch --no-progress --browsers=ChromeHeadless +``` + +NOTE: The `--no-watch` and `--no-progress` flags are crucial for Karma in CI environments to ensure tests run once and exit cleanly. The `--browsers=ChromeHeadless` flag is also essential for running tests in a browser environment without a graphical interface. + +## Debugging tests + +If your tests aren't working as you expect, you can inspect and debug them in the browser. + +To debug an application with the Karma test runner: + +1. Reveal the Karma browser window. See [Set up for testing](guide/testing/overview#configurar-pruebas) if you need help with this step. +2. Click the **DEBUG** button to open a new browser tab and re-run the tests. +3. Open the browser's **Developer Tools**. On Windows, press `Ctrl-Shift-I`. On macOS, press `Command-Option-I`. +4. Pick the **Sources** section. +5. Press `Control/Command-P`, and then start typing the name of your test file to open it. +6. Set a breakpoint in the test. +7. Refresh the browser, and notice how it stops at the breakpoint. + +Karma debugging diff --git a/adev-es/src/content/guide/testing/karma.md b/adev-es/src/content/guide/testing/karma.md index d5d59cf..0a4ca8a 100644 --- a/adev-es/src/content/guide/testing/karma.md +++ b/adev-es/src/content/guide/testing/karma.md @@ -1,24 +1,24 @@ -# Testing with Karma and Jasmine +# Pruebas con Karma y Jasmine -While [Vitest](https://vitest.dev) is the default test runner for new Angular projects, [Karma](https://karma-runner.github.io) is still a supported and widely used test runner. This guide provides instructions for testing your Angular application using the Karma test runner with the [Jasmine](https://jasmine.github.io) testing framework. +Si bien [Vitest](https://vitest.dev) es el ejecutor de pruebas predeterminado para nuevos proyectos en Angular, [Karma](https://karma-runner.github.io) sigue siendo un ejecutor de pruebas compatible y ampliamente utilizado. Esta guía proporciona instrucciones para probar tu aplicación en Angular utilizando el ejecutor de pruebas Karma con el framework de pruebas [Jasmine](https://jasmine.github.io). -## Setting Up Karma and Jasmine +## Configurar Karma y Jasmine -You can set up Karma and Jasmine for a new project or add it to an existing one. +Puedes configurar Karma y Jasmine para un nuevo proyecto o agregarlo a uno existente. -### For New Projects +### Para proyectos nuevos -To create a new project with Karma and Jasmine pre-configured, run the `ng new` command with the `--test-runner=karma` option: +Para crear un nuevo proyecto con Karma y Jasmine preconfigurados, ejecuta el comando `ng new` con la opción `--test-runner=karma`: ```shell ng new my-karma-app --test-runner=karma ``` -### For Existing Projects +### Para proyectos existentes -To add Karma and Jasmine to an existing project, follow these steps: +Para agregar Karma y Jasmine a un proyecto existente, sigue estos pasos: -1. **Install the necessary packages:** +1. **Instala los paquetes necesarios:** @@ -35,9 +35,9 @@ To add Karma and Jasmine to an existing project, follow these steps: -2. **Configure the test runner in `angular.json`:** +2. **Configura el ejecutor de pruebas en `angular.json`:** - In your `angular.json` file, find the `test` target and set the `runner` option to `karma`: + En tu archivo `angular.json`, busca el target `test` y establece la opción `runner` en `karma`: ```json { @@ -50,7 +50,7 @@ To add Karma and Jasmine to an existing project, follow these steps: "builder": "@angular/build:unit-test", "options": { "runner": "karma", - // ... other options + // ... otras opciones } } } @@ -59,9 +59,9 @@ To add Karma and Jasmine to an existing project, follow these steps: } ``` -3. **Update `tsconfig.spec.json` for Jasmine types:** +3. **Actualiza `tsconfig.spec.json` para tipos de Jasmine:** - To ensure TypeScript recognizes global testing functions like `describe` and `it`, add `"jasmine"` to the `types` array in your `tsconfig.spec.json`: + Para asegurar que TypeScript reconozca las funciones globales de pruebas como `describe` e `it`, agrega `"jasmine"` al array `types` en tu `tsconfig.spec.json`: ```json { @@ -76,17 +76,17 @@ To add Karma and Jasmine to an existing project, follow these steps: } ``` -## Running Tests +## Ejecutar pruebas -Once your project is configured, run the tests using the [`ng test`](cli/test) command: +Una vez configurado tu proyecto, ejecuta las pruebas usando el comando [`ng test`](cli/test): ```shell ng test ``` -The `ng test` command builds the application in _watch mode_ and launches the [Karma test runner](https://karma-runner.github.io). +El comando `ng test` construye la aplicación en _modo observación_ e inicia el [ejecutor de pruebas Karma](https://karma-runner.github.io). -The console output looks like below: +La salida en consola se ve como a continuación: ```shell @@ -99,31 +99,31 @@ TOTAL: 3 SUCCESS ``` -The test output is displayed in the browser using [Karma Jasmine HTML Reporter](https://github.com/dfederm/karma-jasmine-html-reporter). +La salida de las pruebas se muestra en el navegador usando [Karma Jasmine HTML Reporter](https://github.com/dfederm/karma-jasmine-html-reporter). -Jasmine HTML Reporter in the browser +Jasmine HTML Reporter en el navegador -Click on a test row to re-run just that test or click on a description to re-run the tests in the selected test group ("test suite"). +Haz clic en una fila de prueba para volver a ejecutar solo esa prueba o haz clic en una descripción para volver a ejecutar las pruebas en el grupo de pruebas seleccionado ("test suite"). -Meanwhile, the `ng test` command is watching for changes. To see this in action, make a small change to a source file and save. The tests run again, the browser refreshes, and the new test results appear. +Mientras tanto, el comando `ng test` está observando cambios. Para ver esto en acción, realiza un pequeño cambio en un archivo fuente y guárdalo. Las pruebas se ejecutan nuevamente, el navegador se actualiza y aparecen los nuevos resultados de las pruebas. -## Configuration +## Configuración -The Angular CLI takes care of Jasmine and Karma configuration for you. It constructs the full configuration in memory, based on options specified in the `angular.json` file. +Angular CLI se encarga de la configuración de Jasmine y Karma por ti. Construye la configuración completa en memoria, basándose en las opciones especificadas en el archivo `angular.json`. -### Customizing Karma Configuration +### Personalizar la configuración de Karma -If you want to customize Karma, you can create a `karma.conf.js` by running the following command: +Si deseas personalizar Karma, puedes crear un `karma.conf.js` ejecutando el siguiente comando: ```shell ng generate config karma ``` -HELPFUL: Read more about Karma configuration in the [Karma configuration guide](http://karma-runner.github.io/6.4/config/configuration-file.html). +ÚTIL: Lee más sobre la configuración de Karma en la [guía de configuración de Karma](http://karma-runner.github.io/6.4/config/configuration-file.html). -### Setting the Test Runner in `angular.json` +### Establecer el ejecutor de pruebas en `angular.json` -To explicitly set Karma as the test runner for your project, locate the `test` target in your `angular.json` file and set the `runner` option to `karma`: +Para establecer explícitamente Karma como el ejecutor de pruebas para tu proyecto, localiza el target `test` en tu archivo `angular.json` y establece la opción `runner` en `karma`: ```json { @@ -136,7 +136,7 @@ To explicitly set Karma as the test runner for your project, locate the `test` t "builder": "@angular/build:unit-test", "options": { "runner": "karma", - // ... other options + // ... otras opciones } } } @@ -145,11 +145,11 @@ To explicitly set Karma as the test runner for your project, locate the `test` t } ``` -## Code coverage enforcement +## Cumplimiento de cobertura de código -To enforce a minimum code coverage level, you can use the `check` property in the `coverageReporter` section of your `karma.conf.js` file. +Para aplicar un nivel mínimo de cobertura de código, puedes usar la propiedad `check` en la sección `coverageReporter` de tu archivo `karma.conf.js`. -For example, to require a minimum of 80% coverage: +Por ejemplo, para requerir un mínimo de 80% de cobertura: ```javascript coverageReporter: { @@ -170,30 +170,30 @@ coverageReporter: { } ``` -This will cause the test run to fail if the specified coverage thresholds are not met. +Esto hará que la ejecución de pruebas falle si no se cumplen los umbrales de cobertura especificados. -## Testing in continuous integration +## Pruebas en integración continua -To run your Karma tests in a CI environment, use the following command: +Para ejecutar tus pruebas de Karma en un entorno de CI, usa el siguiente comando: ```shell ng test --no-watch --no-progress --browsers=ChromeHeadless ``` -NOTE: The `--no-watch` and `--no-progress` flags are crucial for Karma in CI environments to ensure tests run once and exit cleanly. The `--browsers=ChromeHeadless` flag is also essential for running tests in a browser environment without a graphical interface. +NOTA: Las banderas `--no-watch` y `--no-progress` son cruciales para Karma en entornos de CI para asegurar que las pruebas se ejecuten una vez y terminen correctamente. La bandera `--browsers=ChromeHeadless` también es esencial para ejecutar pruebas en un entorno de navegador sin interfaz gráfica. -## Debugging tests +## Depurar pruebas -If your tests aren't working as you expect, you can inspect and debug them in the browser. +Si tus pruebas no están funcionando como esperas, puedes inspeccionarlas y depurarlas en el navegador. -To debug an application with the Karma test runner: +Para depurar una aplicación con el ejecutor de pruebas Karma: -1. Reveal the Karma browser window. See [Set up for testing](guide/testing/overview#configurar-pruebas) if you need help with this step. -2. Click the **DEBUG** button to open a new browser tab and re-run the tests. -3. Open the browser's **Developer Tools**. On Windows, press `Ctrl-Shift-I`. On macOS, press `Command-Option-I`. -4. Pick the **Sources** section. -5. Press `Control/Command-P`, and then start typing the name of your test file to open it. -6. Set a breakpoint in the test. -7. Refresh the browser, and notice how it stops at the breakpoint. +1. Muestra la ventana del navegador de Karma. Consulta [Configurar pruebas](guide/testing/overview#configurar-pruebas) si necesitas ayuda con este paso. +2. Haz clic en el botón **DEBUG** para abrir una nueva pestaña del navegador y volver a ejecutar las pruebas. +3. Abre las **Herramientas para desarrolladores** del navegador. En Windows, presiona `Ctrl-Shift-I`. En macOS, presiona `Command-Option-I`. +4. Selecciona la sección **Sources**. +5. Presiona `Control/Command-P`, y luego comienza a escribir el nombre de tu archivo de prueba para abrirlo. +6. Establece un breakpoint en la prueba. +7. Actualiza el navegador, y nota cómo se detiene en el breakpoint. -Karma debugging +Depuración en Karma diff --git a/adev-es/src/content/guide/testing/migrating-to-vitest.en.md b/adev-es/src/content/guide/testing/migrating-to-vitest.en.md new file mode 100644 index 0000000..eda97ef --- /dev/null +++ b/adev-es/src/content/guide/testing/migrating-to-vitest.en.md @@ -0,0 +1,229 @@ +# Migrating from Karma to Vitest + +The Angular CLI uses [Vitest](https://vitest.dev/) as the default unit test runner for new projects. This guide provides instructions for migrating an existing project from Karma and Jasmine to Vitest. + +IMPORTANT: Migrating an existing project to Vitest is considered experimental. This process also requires the use of the `application` build system, which is the default for all newly created projects. + +## Manual migration steps + +Before using the automated refactoring schematic, you must manually update your project to use the Vitest test runner. + +### 1. Install dependencies + +Install `vitest` and a DOM emulation library. While browser testing is still possible (see [step 5](#5-configure-browser-mode-optional)), Vitest uses a DOM emulation library by default to simulate a browser environment within Node.js for faster test execution. The CLI automatically detects and uses `happy-dom` if it's installed; otherwise, it falls back to `jsdom`. You must have one of these packages installed. + + + + npm install --save-dev vitest jsdom + + + yarn add --dev vitest jsdom + + + pnpm add -D vitest jsdom + + + bun add --dev vitest jsdom + + + +### 2. Update `angular.json` + +In your `angular.json` file, find the `test` target for your project and change the `builder` to `@angular/build:unit-test`. + +```json +{ + "projects": { + "your-project-name": { + "architect": { + "test": { + "builder": "@angular/build:unit-test" + } + } + } + } +} +``` + +The `unit-test` builder defaults to `"tsConfig": "tsconfig.spec.json"` and `"buildTarget": "::development"`. You can explicitly set these options if your project requires different values. For example, if the `development` build configuration is missing or you need different options for testing, you can create and use a `testing` or similarly named build configuration for `buildTarget`. + +The `@angular/build:karma` builder previously allowed build options (like `polyfills`, `assets`, or `styles`) to be configured directly within the `test` target. The new `@angular/build:unit-test` builder does not support this. If your test-specific build options differ from your existing `development` build configuration, you must move them to a dedicated build target configuration. If your test build options already match your `development` build configuration, no action is needed. + +### 3. Handle custom `karma.conf.js` configurations + +Custom configurations in `karma.conf.js` are not automatically migrated. Before deleting your `karma.conf.js` file, review it for any custom settings that need to be migrated. + +Many Karma options have equivalents in Vitest that can be set in a custom Vitest configuration file (e.g., `vitest.config.ts`) and linked to your `angular.json` via the `runnerConfig` option. + +Common migration paths include: + +- **Reporters**: Karma reporters must be replaced with Vitest-compatible reporters. These can often be configured directly in your `angular.json` under the `test.options.reporters` property. For more advanced configurations, use a custom `vitest.config.ts` file. +- **Plugins**: Karma plugins may have Vitest equivalents that you will need to find and install. Note that code coverage is a first-class feature in the Angular CLI and can be enabled with `ng test --coverage`. +- **Custom Browser Launchers**: These are replaced by the `browsers` option in `angular.json` and the installation of a browser provider like `@vitest/browser-playwright`. + +For other settings, consult the official [Vitest documentation](https://vitest.dev/config/). + +### 4. Remove Karma and `test.ts` files + +You can now delete `karma.conf.js` and `src/test.ts` from your project and uninstall the Karma-related packages. The following commands are based on the packages installed in a new Angular CLI project; your project may have other Karma-related packages to remove. + + + + npm uninstall karma karma-chrome-launcher karma-coverage karma-jasmine karma-jasmine-html-reporter + + + yarn remove karma karma-chrome-launcher karma-coverage karma-jasmine karma-jasmine-html-reporter + + + pnpm remove karma karma-chrome-launcher karma-coverage karma-jasmine karma-jasmine-html-reporter + + + bun remove karma karma-chrome-launcher karma-coverage karma-jasmine karma-jasmine-html-reporter + + + +### 5. Configure browser mode (optional) + +If you need to run tests in a real browser, you must install a browser provider and configure your `angular.json`. + +**Install a browser provider:** + +Choose one of the following browser providers based on your needs: + +- **Playwright**: `@vitest/browser-playwright` for Chromium, Firefox, and WebKit. +- **WebdriverIO**: `@vitest/browser-webdriverio` for Chrome, Firefox, Safari, and Edge. +- **Preview**: `@vitest/browser-preview` for Webcontainer environments (like StackBlitz). + + + + npm install --save-dev @vitest/browser-playwright + + + yarn add --dev @vitest/browser-playwright + + + pnpm add -D @vitest/browser-playwright + + + bun add --dev @vitest/browser-playwright + + + +**Update `angular.json` for browser mode:** + +Add the `browsers` option to your `test` target's options. The browser name depends on the provider you installed (e.g., `chromium` for Playwright, `chrome` for WebdriverIO). + +```json +{ + "projects": { + "your-project-name": { + "architect": { + "test": { + "builder": "@angular/build:unit-test", + "options": { + "browsers": ["chromium"] + } + } + } + } + } +} +``` + +Headless mode is enabled automatically if the `CI` environment variable is set or if a browser name includes "Headless" (e.g., `ChromeHeadless`). Otherwise, tests will run in a headed browser. + +## Automated test refactoring with schematics + +IMPORTANT: The `refactor-jasmine-vitest` schematic is experimental and may not cover all possible test patterns. Always review the changes made by the schematic. + +The Angular CLI provides the `refactor-jasmine-vitest` schematic to automatically refactor your Jasmine tests to use Vitest. + +### Overview + +The schematic automates the following transformations in your test files (`.spec.ts`): + +- Converts `fit` and `fdescribe` to `it.only` and `describe.only`. +- Converts `xit` and `xdescribe` to `it.skip` and `describe.skip`. +- Converts `spyOn` calls to the equivalent `vi.spyOn`. +- Replaces `jasmine.objectContaining` with `expect.objectContaining`. +- Replaces `jasmine.any` with `expect.any`. +- Replaces `jasmine.createSpy` with `vi.fn`. +- Updates `beforeAll`, `beforeEach`, `afterAll`, and `afterEach` to their Vitest equivalents. +- Converts `fail()` to Vitest's `vi.fail()`. +- Adjusts expectations to match Vitest APIs +- Adds TODO comments for code that cannot be automatically converted + +The schematic **does not** perform the following actions: + +- It does not install `vitest` or other related dependencies. +- It does not change your `angular.json` to use the Vitest builder or migrate any build options (like `polyfills` or `styles`) from the `test` target. +- It does not remove `karma.conf.js` or `test.ts` files. +- It does not handle complex or nested spy scenarios, which may require manual refactoring. + +### Running the schematic + +Once your project is configured for Vitest, you can run the schematic to refactor your test files. + +To refactor **all** test files in your default project, run: + +```bash +ng g @schematics/angular:refactor-jasmine-vitest +``` + +### Options + +You can use the following options to customize the schematic's behavior: + +| Option | Description | +| :----------------------- | :-------------------------------------------------------------------------------------------------- | +| `--project ` | Specify the project to refactor in a multi-project workspace.
Example: `--project=my-lib` | +| `--include ` | Refactor only a specific file or directory.
Example: `--include=src/app/app.component.spec.ts` | +| `--file-suffix ` | Specify a different file suffix for test files.
Example: `--file-suffix=.test.ts` | +| `--add-imports` | Add explicit `vitest` imports if you have disabled globals in your Vitest configuration. | +| `--verbose` | See detailed logging of all transformations applied. | + +### After migrating + +After the schematic completes, it's a good practice to: + +1. **Run your tests**: Execute `ng test` to ensure that all tests still pass after the refactoring. +2. **Review the changes**: Look over the changes made by the schematic, paying close attention to any complex tests, especially those with intricate spies or mocks, as they may require further manual adjustments. + +The `ng test` command builds the application in _watch mode_ and launches the configured runner. Watch mode is enabled by default when using an interactive terminal and not running on CI. + +## Configuration + +The Angular CLI takes care of the Vitest configuration for you, constructing the full configuration in memory based on options in `angular.json`. + +### Custom Vitest configuration + +IMPORTANT: While using a custom configuration enables advanced options, the Angular team does not provide direct support for the specific contents of the configuration file or for any third-party plugins used within it. The CLI will also override certain properties (`test.projects`, `test.include`) to ensure proper operation. + +You can provide a custom Vitest configuration file to override the default settings. For a full list of available options, see the official [Vitest documentation](https://vitest.dev/config/). + +**1. Direct path:** +Provide a direct path to a Vitest configuration file in your `angular.json`: + +```json +{ + "projects": { + "your-project-name": { + "architect": { + "test": { + "builder": "@angular/build:unit-test", + "options": { "runnerConfig": "vitest.config.ts" } + } + } + } + } +} +``` + +**2. Automatic search for base configuration:** +If you set `runnerConfig` to `true`, the builder will automatically search for a shared `vitest-base.config.*` file in your project and workspace roots. + +## Bug reports + +Report issues and feature requests on [GitHub](https://github.com/angular/angular-cli/issues). + +Please provide a minimal reproduction where possible to aid the team in addressing issues. diff --git a/adev-es/src/content/guide/testing/migrating-to-vitest.md b/adev-es/src/content/guide/testing/migrating-to-vitest.md index eda97ef..7d0bd6a 100644 --- a/adev-es/src/content/guide/testing/migrating-to-vitest.md +++ b/adev-es/src/content/guide/testing/migrating-to-vitest.md @@ -1,16 +1,16 @@ -# Migrating from Karma to Vitest +# Migración de Karma a Vitest -The Angular CLI uses [Vitest](https://vitest.dev/) as the default unit test runner for new projects. This guide provides instructions for migrating an existing project from Karma and Jasmine to Vitest. +Angular CLI usa [Vitest](https://vitest.dev/) como el ejecutor de pruebas unitarias predeterminado para nuevos proyectos. Esta guía proporciona instrucciones para migrar un proyecto existente de Karma y Jasmine a Vitest. -IMPORTANT: Migrating an existing project to Vitest is considered experimental. This process also requires the use of the `application` build system, which is the default for all newly created projects. +IMPORTANTE: Migrar un proyecto existente a Vitest se considera experimental. Este proceso también requiere el uso del sistema de compilación `application`, que es el predeterminado para todos los proyectos recién creados. -## Manual migration steps +## Pasos de migración manual -Before using the automated refactoring schematic, you must manually update your project to use the Vitest test runner. +Antes de usar el schematic de refactorización automatizado, debes actualizar manualmente tu proyecto para usar el ejecutor de pruebas Vitest. -### 1. Install dependencies +### 1. Instalar dependencias -Install `vitest` and a DOM emulation library. While browser testing is still possible (see [step 5](#5-configure-browser-mode-optional)), Vitest uses a DOM emulation library by default to simulate a browser environment within Node.js for faster test execution. The CLI automatically detects and uses `happy-dom` if it's installed; otherwise, it falls back to `jsdom`. You must have one of these packages installed. +Instala `vitest` y una biblioteca de emulación de DOM. Si bien las pruebas en el navegador aún son posibles (consulta el [paso 5](#5-configurar-el-modo-navegador-opcional)), Vitest usa una biblioteca de emulación de DOM de forma predeterminada para simular un entorno de navegador dentro de Node.js para una ejecución de pruebas más rápida. El CLI detecta y usa automáticamente `happy-dom` si está instalado; de lo contrario, recurre a `jsdom`. Debes tener uno de estos paquetes instalados. @@ -27,9 +27,9 @@ Install `vitest` and a DOM emulation library. While browser testing is still pos -### 2. Update `angular.json` +### 2. Actualizar `angular.json` -In your `angular.json` file, find the `test` target for your project and change the `builder` to `@angular/build:unit-test`. +En tu archivo `angular.json`, busca el target `test` para tu proyecto y cambia el `builder` a `@angular/build:unit-test`. ```json { @@ -45,27 +45,27 @@ In your `angular.json` file, find the `test` target for your project and change } ``` -The `unit-test` builder defaults to `"tsConfig": "tsconfig.spec.json"` and `"buildTarget": "::development"`. You can explicitly set these options if your project requires different values. For example, if the `development` build configuration is missing or you need different options for testing, you can create and use a `testing` or similarly named build configuration for `buildTarget`. +El builder `unit-test` tiene como valor predeterminado `"tsConfig": "tsconfig.spec.json"` y `"buildTarget": "::development"`. Puedes establecer explícitamente estas opciones si tu proyecto requiere valores diferentes. Por ejemplo, si falta la configuración de compilación `development` o necesitas opciones diferentes para las pruebas, puedes crear y usar una configuración de compilación `testing` o con nombre similar para `buildTarget`. -The `@angular/build:karma` builder previously allowed build options (like `polyfills`, `assets`, or `styles`) to be configured directly within the `test` target. The new `@angular/build:unit-test` builder does not support this. If your test-specific build options differ from your existing `development` build configuration, you must move them to a dedicated build target configuration. If your test build options already match your `development` build configuration, no action is needed. +El builder `@angular/build:karma` anteriormente permitía que las opciones de compilación (como `polyfills`, `assets` o `styles`) se configuraran directamente dentro del target `test`. El nuevo builder `@angular/build:unit-test` no admite esto. Si tus opciones de compilación específicas para pruebas difieren de tu configuración de compilación `development` existente, debes moverlas a una configuración de target de compilación dedicada. Si tus opciones de compilación de pruebas ya coinciden con tu configuración de compilación `development`, no se requiere ninguna acción. -### 3. Handle custom `karma.conf.js` configurations +### 3. Manejar configuraciones personalizadas de `karma.conf.js` -Custom configurations in `karma.conf.js` are not automatically migrated. Before deleting your `karma.conf.js` file, review it for any custom settings that need to be migrated. +Las configuraciones personalizadas en `karma.conf.js` no se migran automáticamente. Antes de eliminar tu archivo `karma.conf.js`, revísalo para detectar cualquier configuración personalizada que necesite ser migrada. -Many Karma options have equivalents in Vitest that can be set in a custom Vitest configuration file (e.g., `vitest.config.ts`) and linked to your `angular.json` via the `runnerConfig` option. +Muchas opciones de Karma tienen equivalentes en Vitest que se pueden establecer en un archivo de configuración personalizado de Vitest (por ejemplo, `vitest.config.ts`) y vincularlo a tu `angular.json` a través de la opción `runnerConfig`. -Common migration paths include: +Las rutas de migración comunes incluyen: -- **Reporters**: Karma reporters must be replaced with Vitest-compatible reporters. These can often be configured directly in your `angular.json` under the `test.options.reporters` property. For more advanced configurations, use a custom `vitest.config.ts` file. -- **Plugins**: Karma plugins may have Vitest equivalents that you will need to find and install. Note that code coverage is a first-class feature in the Angular CLI and can be enabled with `ng test --coverage`. -- **Custom Browser Launchers**: These are replaced by the `browsers` option in `angular.json` and the installation of a browser provider like `@vitest/browser-playwright`. +- **Reporters**: Los reporters de Karma deben reemplazarse con reporters compatibles con Vitest. Estos a menudo se pueden configurar directamente en tu `angular.json` bajo la propiedad `test.options.reporters`. Para configuraciones más avanzadas, usa un archivo personalizado `vitest.config.ts`. +- **Plugins**: Los plugins de Karma pueden tener equivalentes en Vitest que necesitarás encontrar e instalar. Ten en cuenta que la cobertura de código es una característica de primera clase en Angular CLI y se puede habilitar con `ng test --coverage`. +- **Custom Browser Launchers**: Estos son reemplazados por la opción `browsers` en `angular.json` y la instalación de un proveedor de navegador como `@vitest/browser-playwright`. -For other settings, consult the official [Vitest documentation](https://vitest.dev/config/). +Para otras configuraciones, consulta la [documentación oficial de Vitest](https://vitest.dev/config/). -### 4. Remove Karma and `test.ts` files +### 4. Eliminar archivos de Karma y `test.ts` -You can now delete `karma.conf.js` and `src/test.ts` from your project and uninstall the Karma-related packages. The following commands are based on the packages installed in a new Angular CLI project; your project may have other Karma-related packages to remove. +Ahora puedes eliminar `karma.conf.js` y `src/test.ts` de tu proyecto y desinstalar los paquetes relacionados con Karma. Los siguientes comandos se basan en los paquetes instalados en un nuevo proyecto de Angular CLI; tu proyecto puede tener otros paquetes relacionados con Karma para eliminar. @@ -82,17 +82,17 @@ You can now delete `karma.conf.js` and `src/test.ts` from your project and unins -### 5. Configure browser mode (optional) +### 5. Configurar el modo navegador (opcional) -If you need to run tests in a real browser, you must install a browser provider and configure your `angular.json`. +Si necesitas ejecutar pruebas en un navegador real, debes instalar un proveedor de navegador y configurar tu `angular.json`. -**Install a browser provider:** +**Instalar un proveedor de navegador:** -Choose one of the following browser providers based on your needs: +Elige uno de los siguientes proveedores de navegador según tus necesidades: -- **Playwright**: `@vitest/browser-playwright` for Chromium, Firefox, and WebKit. -- **WebdriverIO**: `@vitest/browser-webdriverio` for Chrome, Firefox, Safari, and Edge. -- **Preview**: `@vitest/browser-preview` for Webcontainer environments (like StackBlitz). +- **Playwright**: `@vitest/browser-playwright` para Chromium, Firefox y WebKit. +- **WebdriverIO**: `@vitest/browser-webdriverio` para Chrome, Firefox, Safari y Edge. +- **Preview**: `@vitest/browser-preview` para entornos Webcontainer (como StackBlitz). @@ -109,9 +109,9 @@ Choose one of the following browser providers based on your needs: -**Update `angular.json` for browser mode:** +**Actualizar `angular.json` para modo navegador:** -Add the `browsers` option to your `test` target's options. The browser name depends on the provider you installed (e.g., `chromium` for Playwright, `chrome` for WebdriverIO). +Agrega la opción `browsers` a las opciones del target `test`. El nombre del navegador depende del proveedor que instalaste (por ejemplo, `chromium` para Playwright, `chrome` para WebdriverIO). ```json { @@ -130,79 +130,79 @@ Add the `browsers` option to your `test` target's options. The browser name depe } ``` -Headless mode is enabled automatically if the `CI` environment variable is set or if a browser name includes "Headless" (e.g., `ChromeHeadless`). Otherwise, tests will run in a headed browser. +El modo headless se habilita automáticamente si la variable de entorno `CI` está configurada o si el nombre de un navegador incluye "Headless" (por ejemplo, `ChromeHeadless`). De lo contrario, las pruebas se ejecutarán en un navegador con interfaz gráfica. -## Automated test refactoring with schematics +## Refactorización automatizada de pruebas con schematics -IMPORTANT: The `refactor-jasmine-vitest` schematic is experimental and may not cover all possible test patterns. Always review the changes made by the schematic. +IMPORTANTE: El schematic `refactor-jasmine-vitest` es experimental y puede no cubrir todos los patrones de prueba posibles. Siempre revisa los cambios realizados por el schematic. -The Angular CLI provides the `refactor-jasmine-vitest` schematic to automatically refactor your Jasmine tests to use Vitest. +Angular CLI proporciona el schematic `refactor-jasmine-vitest` para refactorizar automáticamente tus pruebas de Jasmine para usar Vitest. -### Overview +### Descripción general -The schematic automates the following transformations in your test files (`.spec.ts`): +El schematic automatiza las siguientes transformaciones en tus archivos de prueba (`.spec.ts`): -- Converts `fit` and `fdescribe` to `it.only` and `describe.only`. -- Converts `xit` and `xdescribe` to `it.skip` and `describe.skip`. -- Converts `spyOn` calls to the equivalent `vi.spyOn`. -- Replaces `jasmine.objectContaining` with `expect.objectContaining`. -- Replaces `jasmine.any` with `expect.any`. -- Replaces `jasmine.createSpy` with `vi.fn`. -- Updates `beforeAll`, `beforeEach`, `afterAll`, and `afterEach` to their Vitest equivalents. -- Converts `fail()` to Vitest's `vi.fail()`. -- Adjusts expectations to match Vitest APIs -- Adds TODO comments for code that cannot be automatically converted +- Convierte `fit` y `fdescribe` a `it.only` y `describe.only`. +- Convierte `xit` y `xdescribe` a `it.skip` y `describe.skip`. +- Convierte las llamadas `spyOn` al equivalente `vi.spyOn`. +- Reemplaza `jasmine.objectContaining` con `expect.objectContaining`. +- Reemplaza `jasmine.any` con `expect.any`. +- Reemplaza `jasmine.createSpy` con `vi.fn`. +- Actualiza `beforeAll`, `beforeEach`, `afterAll` y `afterEach` a sus equivalentes en Vitest. +- Convierte `fail()` al `vi.fail()` de Vitest. +- Ajusta las expectativas para que coincidan con las APIs de Vitest +- Agrega comentarios TODO para código que no se puede convertir automáticamente -The schematic **does not** perform the following actions: +El schematic **no** realiza las siguientes acciones: -- It does not install `vitest` or other related dependencies. -- It does not change your `angular.json` to use the Vitest builder or migrate any build options (like `polyfills` or `styles`) from the `test` target. -- It does not remove `karma.conf.js` or `test.ts` files. -- It does not handle complex or nested spy scenarios, which may require manual refactoring. +- No instala `vitest` u otras dependencias relacionadas. +- No cambia tu `angular.json` para usar el builder de Vitest ni migra ninguna opción de compilación (como `polyfills` o `styles`) del target `test`. +- No elimina los archivos `karma.conf.js` o `test.ts`. +- No maneja escenarios de spy complejos o anidados, que pueden requerir refactorización manual. -### Running the schematic +### Ejecutar el schematic -Once your project is configured for Vitest, you can run the schematic to refactor your test files. +Una vez que tu proyecto esté configurado para Vitest, puedes ejecutar el schematic para refactorizar tus archivos de prueba. -To refactor **all** test files in your default project, run: +Para refactorizar **todos** los archivos de prueba en tu proyecto predeterminado, ejecuta: ```bash ng g @schematics/angular:refactor-jasmine-vitest ``` -### Options +### Opciones -You can use the following options to customize the schematic's behavior: +Puedes usar las siguientes opciones para personalizar el comportamiento del schematic: -| Option | Description | -| :----------------------- | :-------------------------------------------------------------------------------------------------- | -| `--project ` | Specify the project to refactor in a multi-project workspace.
Example: `--project=my-lib` | -| `--include ` | Refactor only a specific file or directory.
Example: `--include=src/app/app.component.spec.ts` | -| `--file-suffix ` | Specify a different file suffix for test files.
Example: `--file-suffix=.test.ts` | -| `--add-imports` | Add explicit `vitest` imports if you have disabled globals in your Vitest configuration. | -| `--verbose` | See detailed logging of all transformations applied. | +| Opción | Descripción | +| :----------------------- | :------------------------------------------------------------------------------------------------------------------ | +| `--project ` | Especifica el proyecto a refactorizar en un workspace con múltiples proyectos.
Ejemplo: `--project=my-lib` | +| `--include ` | Refactoriza solo un archivo o directorio específico.
Ejemplo: `--include=src/app/app.component.spec.ts` | +| `--file-suffix ` | Especifica un sufijo de archivo diferente para archivos de prueba.
Ejemplo: `--file-suffix=.test.ts` | +| `--add-imports` | Agrega imports explícitos de `vitest` si has deshabilitado los globales en tu configuración de Vitest. | +| `--verbose` | Muestra el registro detallado de todas las transformaciones aplicadas. | -### After migrating +### Después de migrar -After the schematic completes, it's a good practice to: +Después de que se complete el schematic, es una buena práctica: -1. **Run your tests**: Execute `ng test` to ensure that all tests still pass after the refactoring. -2. **Review the changes**: Look over the changes made by the schematic, paying close attention to any complex tests, especially those with intricate spies or mocks, as they may require further manual adjustments. +1. **Ejecuta tus pruebas**: Ejecuta `ng test` para asegurar que todas las pruebas aún pasen después de la refactorización. +2. **Revisa los cambios**: Revisa los cambios realizados por el schematic, prestando especial atención a cualquier prueba compleja, especialmente aquellas con spies o mocks intrincados, ya que pueden requerir ajustes manuales adicionales. -The `ng test` command builds the application in _watch mode_ and launches the configured runner. Watch mode is enabled by default when using an interactive terminal and not running on CI. +El comando `ng test` construye la aplicación en _modo observación_ e inicia el ejecutor configurado. El modo observación está habilitado de forma predeterminada cuando se usa un terminal interactivo y no se ejecuta en CI. -## Configuration +## Configuración -The Angular CLI takes care of the Vitest configuration for you, constructing the full configuration in memory based on options in `angular.json`. +Angular CLI se encarga de la configuración de Vitest por ti, construyendo la configuración completa en memoria basándose en las opciones en `angular.json`. -### Custom Vitest configuration +### Configuración personalizada de Vitest -IMPORTANT: While using a custom configuration enables advanced options, the Angular team does not provide direct support for the specific contents of the configuration file or for any third-party plugins used within it. The CLI will also override certain properties (`test.projects`, `test.include`) to ensure proper operation. +IMPORTANTE: Si bien usar una configuración personalizada habilita opciones avanzadas, el equipo de Angular no proporciona soporte directo para el contenido específico del archivo de configuración ni para ningún plugin de terceros utilizado dentro de él. El CLI también sobrescribirá ciertas propiedades (`test.projects`, `test.include`) para garantizar el funcionamiento adecuado. -You can provide a custom Vitest configuration file to override the default settings. For a full list of available options, see the official [Vitest documentation](https://vitest.dev/config/). +Puedes proporcionar un archivo de configuración personalizado de Vitest para sobrescribir la configuración predeterminada. Para obtener una lista completa de opciones disponibles, consulta la [documentación oficial de Vitest](https://vitest.dev/config/). -**1. Direct path:** -Provide a direct path to a Vitest configuration file in your `angular.json`: +**1. Ruta directa:** +Proporciona una ruta directa a un archivo de configuración de Vitest en tu `angular.json`: ```json { @@ -219,11 +219,11 @@ Provide a direct path to a Vitest configuration file in your `angular.json`: } ``` -**2. Automatic search for base configuration:** -If you set `runnerConfig` to `true`, the builder will automatically search for a shared `vitest-base.config.*` file in your project and workspace roots. +**2. Búsqueda automática de configuración base:** +Si estableces `runnerConfig` en `true`, el builder buscará automáticamente un archivo compartido `vitest-base.config.*` en las raíces de tu proyecto y workspace. -## Bug reports +## Reporte de errores -Report issues and feature requests on [GitHub](https://github.com/angular/angular-cli/issues). +Reporta problemas y solicitudes de características en [GitHub](https://github.com/angular/angular-cli/issues). -Please provide a minimal reproduction where possible to aid the team in addressing issues. +Proporciona una reproducción mínima cuando sea posible para ayudar al equipo a abordar los problemas. diff --git a/adev-es/src/content/guide/testing/zone-js-testing-utilities.en.md b/adev-es/src/content/guide/testing/zone-js-testing-utilities.en.md new file mode 100644 index 0000000..a90cddf --- /dev/null +++ b/adev-es/src/content/guide/testing/zone-js-testing-utilities.en.md @@ -0,0 +1,15 @@ +# Zone.js Testing Utilities + +This guide describes testing utilities primarily used for managing and controlling async tasks in unit tests. These utilities are essentially the Zone.js-specific mock clock utilities, particularly relevant for controlling the flow of asynchronous operations within tests. + +For general Angular testing utilities, including `TestBed` and `ComponentFixture`, see the [Testing Utility APIs](guide/testing/utility-apis) guide. + +Here's a summary of Zone.js-specific functions: + +| Function | Details | +| :--------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `waitForAsync` | Tracks async tasks and completes the tests only once there are no longer any micro or macrotasks remaining in the test zone. See [waitForAsync](guide/testing/components-scenarios#prueba-async-sin-fakeasync). | +| `fakeAsync` | Runs the body of a test \(`it`\) within a special _fakeAsync test zone_, enabling a linear control flow coding style. See [fakeAsync](guide/testing/components-scenarios#prueba-async-con-fakeasync). | +| `tick` | Simulates the passage of time and the completion of pending asynchronous activities by flushing both _timer_ and _micro-task_ queues within the _fakeAsync test zone_. The curious, dedicated reader might enjoy this lengthy blog post, ["_Tasks, microtasks, queues and schedules_"](https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules). Accepts an optional argument that moves the virtual clock forward by the specified number of milliseconds, clearing asynchronous activities scheduled within that timeframe. See [tick](guide/testing/components-scenarios#la-función-tick). | +| `discardPeriodicTasks` | Discards any periodic tasks (e.g. `setInterval`) that were created inside the `fakeAsync` Zone. | +| `flushMicrotasks` | When a `fakeAsync()` test ends with pending _micro-tasks_ such as unresolved promises, the test fails with a clear error message.
In general, a test should wait for micro-tasks to finish. When pending microtasks are expected, call `flushMicrotasks` to flush the _micro-task_ queue and avoid the error. | diff --git a/adev-es/src/content/guide/testing/zone-js-testing-utilities.md b/adev-es/src/content/guide/testing/zone-js-testing-utilities.md index a90cddf..d8e0860 100644 --- a/adev-es/src/content/guide/testing/zone-js-testing-utilities.md +++ b/adev-es/src/content/guide/testing/zone-js-testing-utilities.md @@ -1,15 +1,15 @@ -# Zone.js Testing Utilities +# Utilidades de pruebas de Zone.js -This guide describes testing utilities primarily used for managing and controlling async tasks in unit tests. These utilities are essentially the Zone.js-specific mock clock utilities, particularly relevant for controlling the flow of asynchronous operations within tests. +Esta guía describe las utilidades de pruebas utilizadas principalmente para gestionar y controlar tareas asíncronas en pruebas unitarias. Estas utilidades son esencialmente las utilidades de reloj mock específicas de Zone.js, particularmente relevantes para controlar el flujo de operaciones asíncronas dentro de las pruebas. -For general Angular testing utilities, including `TestBed` and `ComponentFixture`, see the [Testing Utility APIs](guide/testing/utility-apis) guide. +Para utilidades generales de pruebas en Angular, incluyendo `TestBed` y `ComponentFixture`, consulta la guía [APIs de utilidades de pruebas](guide/testing/utility-apis). -Here's a summary of Zone.js-specific functions: +Aquí hay un resumen de las funciones específicas de Zone.js: -| Function | Details | -| :--------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `waitForAsync` | Tracks async tasks and completes the tests only once there are no longer any micro or macrotasks remaining in the test zone. See [waitForAsync](guide/testing/components-scenarios#prueba-async-sin-fakeasync). | -| `fakeAsync` | Runs the body of a test \(`it`\) within a special _fakeAsync test zone_, enabling a linear control flow coding style. See [fakeAsync](guide/testing/components-scenarios#prueba-async-con-fakeasync). | -| `tick` | Simulates the passage of time and the completion of pending asynchronous activities by flushing both _timer_ and _micro-task_ queues within the _fakeAsync test zone_. The curious, dedicated reader might enjoy this lengthy blog post, ["_Tasks, microtasks, queues and schedules_"](https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules). Accepts an optional argument that moves the virtual clock forward by the specified number of milliseconds, clearing asynchronous activities scheduled within that timeframe. See [tick](guide/testing/components-scenarios#la-función-tick). | -| `discardPeriodicTasks` | Discards any periodic tasks (e.g. `setInterval`) that were created inside the `fakeAsync` Zone. | -| `flushMicrotasks` | When a `fakeAsync()` test ends with pending _micro-tasks_ such as unresolved promises, the test fails with a clear error message.
In general, a test should wait for micro-tasks to finish. When pending microtasks are expected, call `flushMicrotasks` to flush the _micro-task_ queue and avoid the error. | +| Función | Detalles | +| :--------------------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `waitForAsync` | Rastrea tareas asíncronas y completa las pruebas solo una vez que ya no quedan micro-tareas o macro-tareas pendientes en la zona de prueba. Consulta [waitForAsync](guide/testing/components-scenarios#prueba-async-sin-fakeasync). | +| `fakeAsync` | Ejecuta el cuerpo de una prueba \\(`it`\\) dentro de una _zona de prueba fakeAsync_ especial, habilitando un estilo de codificación de flujo de control lineal. Consulta [fakeAsync](guide/testing/components-scenarios#prueba-async-con-fakeasync). | +| `tick` | Simula el paso del tiempo y la finalización de actividades asíncronas pendientes vaciando tanto las colas de _temporizadores_ como de _micro-tareas_ dentro de la _zona de prueba fakeAsync_. El lector curioso y dedicado podría disfrutar esta extensa publicación de blog, [\"_Tasks, microtasks, queues and schedules_\"](https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules). Acepta un argumento opcional que mueve el reloj virtual hacia adelante por el número especificado de milisegundos, limpiando las actividades asíncronas programadas dentro de ese período de tiempo. Consulta [tick](guide/testing/components-scenarios#la-función-tick). | +| `discardPeriodicTasks` | Descarta cualquier tarea periódica (por ejemplo, `setInterval`) que fue creada dentro de la zona `fakeAsync`. | +| `flushMicrotasks` | Cuando una prueba `fakeAsync()` termina con _micro-tareas_ pendientes, como promesas no resueltas, la prueba falla con un mensaje de error claro.
En general, una prueba debe esperar a que las micro-tareas terminen. Cuando se esperan micro-tareas pendientes, llama a `flushMicrotasks` para vaciar la cola de _micro-tareas_ y evitar el error. |