### Practical Test Setup with Setup Functions Source: https://github.com/avajs/ava/blob/main/docs/recipes/test-setup.md Use plain setup functions to create and configure test data, allowing for parameterization to customize setup for different tests. This approach avoids the 'magic' of hooks and offers more explicit control. ```javascript function setup({username = 'admin', password = 's3cr3t'} = {}) { return { authenticator: new Authenticator(), credentials: new Credentials(username, password) }; } test('authenticating with valid credentials', async t => { const {authenticator, credentials} = setup(); const isValid = authenticator.authenticate(credentials); t.true(await isValid); }); test('authenticating with an invalid username', async t => { const {authenticator, credentials} = setup({username: 'bad_username'}); const isValid = authenticator.authenticate(credentials); t.false(await isValid); }); test('authenticating with an invalid password', async t => { const {authenticator, credentials} = setup({password: 'bad_password'}); const isValid = authenticator.authenticate(credentials); t.false(await isValid); }); ``` -------------------------------- ### Practical Test Setup with `beforeEach()` Source: https://github.com/avajs/ava/blob/main/docs/recipes/test-setup.md Initialize context with common objects like authenticators and credentials in `beforeEach()` for reuse across tests. This example demonstrates authenticating with valid and invalid credentials. ```javascript test.beforeEach(t => { t.context = { authenticator: new Authenticator(), credentials: new Credentials('admin', 's3cr3t') }; }); test('authenticating with valid credentials', async t => { const isValid = t.context.authenticator.authenticate(t.context.credentials); t.true(await isValid); }); test('authenticating with an invalid username', async t => { t.context.credentials.username = 'bad_username'; const isValid = t.context.authenticator.authenticate(t.context.credentials); t.false(await isValid); }); test('authenticating with an invalid password', async t => { t.context.credentials.password = 'bad_password'; const isValid = t.context.authenticator.authenticate(t.context.credentials); t.false(await isValid); }); ``` -------------------------------- ### Combining `beforeEach()` and Setup Functions Source: https://github.com/avajs/ava/blob/main/docs/recipes/test-setup.md Integrate `beforeEach()` for common setup across all tests with specific setup functions called within individual tests for tailored configurations. ```javascript test.beforeEach(t => { t.context = setupAllTests(); }); test('first scenario', t => { firstSetup(t); const someCondition = t.context.thingUnderTest(); t.true(someCondition); }); ``` -------------------------------- ### Install Dependencies Source: https://github.com/avajs/ava/blob/main/docs/recipes/testing-with-selenium-webdriverjs.md Install selenium-webdriver and chromedriver using npm. ```bash npm install selenium-webdriver chromedriver ``` -------------------------------- ### Start MongoDB Server in AVA Tests Source: https://github.com/avajs/ava/blob/main/docs/recipes/isolated-mongodb-integration-tests.md Import MongoMem and start the MongoDB server before your tests run. Ensure the server is started outside of any test cases. ```javascript import test from 'ava'; import {MongoDBServer} from 'mongomem'; test.before('start server', async t => { await MongoDBServer.start(); }) test('some feature', async t => { const connectionString = await MongoDBServer.getConnectionString(); // connectionString === 'mongodb://localhost:27017/3411fd12-b5d6-4860-854c-5bbdb011cb93' // Use `connectionString` to connect to the database with a client of your choice. See below for usage with Mongoose. }); ``` -------------------------------- ### Setup In-Memory MongoDB and Mongoose Connection Source: https://github.com/avajs/ava/blob/main/docs/recipes/endpoint-testing-with-mongoose.md Use AVA's `test.before` hook to start an in-memory MongoDB server and establish a Mongoose connection before tests run. ```javascript // Create connection to Mongoose before tests are run test.before(async t => { // First start MongoDB instance t.context.mongod = await MongoMemoryServer.create(); // And connect await mongoose.connect(t.context.mongod.getUri()); }); ``` -------------------------------- ### Install Testing Libraries Source: https://github.com/avajs/ava/blob/main/docs/recipes/endpoint-testing-with-mongoose.md Install the necessary development dependencies for in-memory MongoDB and endpoint testing. ```bash $ npm install --save-dev mongodb-memory-server supertest ``` ```bash $ npm install mongoose ``` -------------------------------- ### Complex Test Setup with `beforeEach()` Source: https://github.com/avajs/ava/blob/main/docs/recipes/test-setup.md Use `beforeEach()` for setup steps that apply to all tests in a file. Modifications can then be made within individual tests. ```javascript test.beforeEach(t => { supConditionA(t); supConditionB(t); supConditionC(t); }); test('first scenario', t => { tweakSomething(t); const someCondition = t.context.thingUnderTest(); t.true(someCondition); }); test('second scenario', t => { tweakSomethingElse(t); const someOtherCondition = t.context.thingUnderTest(); t.true(someOtherCondition); }); ``` -------------------------------- ### Install AVA with Yarn Source: https://github.com/avajs/ava/blob/main/readme.md If you prefer using Yarn, install AVA as a development dependency with this command. ```console yarn add ava --dev ``` -------------------------------- ### AVA package.json Configuration Source: https://github.com/avajs/ava/blob/main/readme.md This is an example of how your package.json should look after initializing AVA. Ensure the 'test' script points to 'ava'. ```json { "name": "awesome-package", "type": "module", "scripts": { "test": "ava" }, "devDependencies": { "ava": "^5.0.0" } } ``` -------------------------------- ### Install c8 Source: https://github.com/avajs/ava/blob/main/docs/recipes/code-coverage.md Install c8 as a development dependency using npm. ```bash $ npm install --save-dev c8 ``` -------------------------------- ### Complex Test Setup without `beforeEach()` Source: https://github.com/avajs/ava/blob/main/docs/recipes/test-setup.md Omit `beforeEach()` and perform all setup steps within individual tests when many variables need changing per test. This allows selective setup, as shown where `setupConditionB()` is not called. ```javascript test('first scenario', t => { supConditionA(t); supConditionB(t, {/* options */}); supConditionC(t); const someCondition = t.context.thingUnderTest(); t.true(someCondition); }); // In this test, setupConditionB() is never called. test('second scenario', t => { supConditionA(t); supConditionC(t); const someOtherCondition = t.context.thingUnderTest(); t.true(someOtherCondition); }); ``` -------------------------------- ### Install MongoMem Source: https://github.com/avajs/ava/blob/main/docs/recipes/isolated-mongodb-integration-tests.md Install the MongoMem package as a development dependency in your project. ```bash npm install --save-dev mongomem ``` -------------------------------- ### AVA CLI Usage Examples Source: https://github.com/avajs/ava/blob/main/docs/05-command-line.md Illustrates common ways to invoke the AVA CLI, including running all tests, targeting specific files, and running tests on particular lines. ```console Examples: ava ava test.js ava test.js:4,7-9 ``` -------------------------------- ### Install jsdom Source: https://github.com/avajs/ava/blob/main/docs/recipes/browser-testing.md Install jsdom as a development dependency using npm. ```bash npm install --save-dev jsdom ``` -------------------------------- ### Install AVA Manually Source: https://github.com/avajs/ava/blob/main/readme.md Alternatively, you can install AVA manually as a dev dependency. Remember AVA cannot be run globally. ```console npm install --save-dev ava ``` -------------------------------- ### Setup Puppeteer Page Helper Source: https://github.com/avajs/ava/blob/main/docs/recipes/puppeteer.md Configure a helper function to launch a Puppeteer browser and page for testing. This ensures proper setup and teardown of browser instances. ```javascript import puppeteer from 'puppeteer'; export default async (t, run) => { const browser = await puppeteer.launch(); const page = await browser.newPage(); try { await run(t, page); } finally { await page.close(); await browser.close(); } }; ``` -------------------------------- ### Requiring Installed Modules in AVA Source: https://github.com/avajs/ava/blob/main/docs/06-configuration.md Load modules installed in `node_modules` before test files are executed. This example shows requiring `@babel/register`. ```javascript export default { require: '@babel/register' } ``` -------------------------------- ### Setup and Teardown Hooks for Google Tests Source: https://github.com/avajs/ava/blob/main/docs/recipes/testing-with-selenium-webdriverjs.md Use AVA's `beforeEach` and `afterEach` hooks to initialize and close the WebDriver instance for each test, reducing code duplication. ```javascript test.beforeEach(async t => { t.context.driver = new Builder().forBrowser('chrome').build(); await t.context.driver.get('https://www.google.com'); }); test.afterEach('cleanup', async t => { await t.context.driver.close(); }); ``` -------------------------------- ### Basic AVA Test File Source: https://github.com/avajs/ava/blob/main/readme.md Create a 'test.js' file to write your tests. AVA assumes ES modules by default. This example shows a simple passing test and an async test. ```javascript import test from 'ava'; test('foo', t => { t.pass(); }); test('bar', async t => { const bar = Promise.resolve('bar'); t.is(await bar, 'bar'); }); ``` -------------------------------- ### Basic TypeScript Test with AVA Source: https://github.com/avajs/ava/blob/main/docs/recipes/typescript.md Write a simple test file in TypeScript using ESM syntax. This example demonstrates a basic test case for a function. ```typescript import test from 'ava'; const fn = () => 'foo'; test('fn() returns foo', t => { tt.is(fn(), 'foo'); }); ``` -------------------------------- ### Test HTTP Endpoints with AVA Source: https://github.com/avajs/ava/blob/main/docs/recipes/endpoint-testing.md Use `ky` to make HTTP requests and `async-listen` to start a server. Ensure server cleanup with `test.after.always`. Tests are run serially to avoid port conflicts. ```javascript import {createServer} from 'node:http'; import {listen} from 'async-listen'; import test from 'ava'; import ky, {HTTPError} from 'ky'; import app from './app.js'; test.before(async t => { t.context.server = createServer(app); t.context.prefixUrl = await listen(t.context.server); }); test.after.always(t => { tt.context.server.close(); }); test.serial('get /user', async t => { const {email} = await ky('user', {prefixUrl: t.context.prefixUrl}).json(); t t.is(email, 'ava@rocks.com'); }); test.serial('404', async t => { await t.throwsAsync( ky('password', {prefixUrl: t.context.prefixUrl}), {message: /Request failed with status code 404 Not Found/, instanceOf: HTTPError}, ); }); ``` -------------------------------- ### AVA Configuration with ava.config.js Source: https://github.com/avajs/ava/blob/main/docs/06-configuration.md Use `ava.config.js` when your project treats `.js` files as ES modules. This example shows a basic configuration object. ```javascript export default { require: ['./_my-test-helper.js'] }; ``` -------------------------------- ### Customizing Test Files with CLI Config Source: https://github.com/avajs/ava/blob/main/docs/06-configuration.md Specify a custom configuration file using the `--config` flag. This example shows how to filter tests for unit or integration runs. ```javascript export default { files: ['unit-tests/**/*'] }; ``` ```javascript import baseConfig from './ava.config.js'; export default { ...baseConfig, files: ['integration-tests/**/*'] }; ``` -------------------------------- ### Enable Debugging for MongoDB Server Source: https://github.com/avajs/ava/blob/main/docs/recipes/isolated-mongodb-integration-tests.md Set `MongoDBServer.debug = true;` before starting the server to enable detailed logging for connection or file permission errors. ```javascript MongoDBServer.debug = true; ``` -------------------------------- ### Requiring Extra Modules in AVA (Single Path) Source: https://github.com/avajs/ava/blob/main/docs/06-configuration.md Use the `require` option in `ava.config.js` to load extra modules before test files. This example shows loading a single helper file. ```javascript export default { require: './_my-test-helper.js' } ``` -------------------------------- ### Run tests matching titles starting with 'foo' Source: https://github.com/avajs/ava/blob/main/docs/05-command-line.md Use the `--match` flag with a wildcard pattern to filter tests by their titles. Patterns are case-insensitive. ```bash npx ava --match='foo*' ``` -------------------------------- ### Test GET Endpoint with SuperTest Source: https://github.com/avajs/ava/blob/main/docs/recipes/endpoint-testing-with-mongoose.md Send a GET request to the '/litmus' endpoint using SuperTest and assert the response status and body content with AVA. ```javascript // Note that the tests are run serially. See below as to why. test.serial('litmus get user', async t => { const {app} = t.context; const res = await request(app) .get('/litmus') .send({email: 'one@example.com'}); t is(res.status, 200); t is(res.body.name, 'One'); }); ``` -------------------------------- ### Run tests matching titles starting with 'foo' OR ending with 'bar' Source: https://github.com/avajs/ava/blob/main/docs/05-command-line.md Use multiple `--match` flags to specify alternative wildcard patterns for filtering test titles. Patterns are case-insensitive. ```bash npx ava --match='foo*' --match='*bar' ``` -------------------------------- ### TypeScript Context Typing in Ava Source: https://github.com/avajs/ava/blob/main/examples/typescript-context/readme.md Example of how to type `t.context` in Ava tests using TypeScript. Ensure your test file is named with a `.ts` extension and that TypeScript is configured. ```typescript import test from 'ava'; interface TestContext { foo: string; } test.serial('typed context', (t) => { t.context.foo = 'bar'; // t.context.foo is typed as string }); test('another test', (t) => { // t.context.foo is typed as string }); ``` -------------------------------- ### Marco Polo Game Example Source: https://github.com/avajs/ava/blob/main/docs/recipes/shared-workers.md Illustrates message passing and replies between test workers and the shared worker using a recursive 'Marco Polo' game. Note that setting up many reply listeners can be inefficient. ```javascript export default ({negotiateProtocol}) => { const main = negotiateProtocol(['ava-4']).ready(); play(main.subscribe()); }; const play = async (messages) => { for await (const message of messages) { if (message.data === 'Marco') { const response = message.reply('Polo'); play(response.replies()); } } } ``` -------------------------------- ### Run tests matching titles starting with 'foo' and ending with 'bar' Source: https://github.com/avajs/ava/blob/main/docs/05-command-line.md Use the `--match` flag with a combined wildcard pattern to filter tests by titles that meet multiple criteria. Patterns are case-insensitive. ```bash npx ava --match='foo*bar' ``` -------------------------------- ### Initialize AVA Project Source: https://github.com/avajs/ava/blob/main/readme.md Use this command to initialize AVA in your project. It automatically configures your package.json. ```console npm init ava ``` -------------------------------- ### Populate Database Before Each Test Source: https://github.com/avajs/ava/blob/main/docs/recipes/endpoint-testing-with-mongoose.md Use AVA's `test.beforeEach` hook to insert dummy data into the database before each test case. ```javascript test.beforeEach(async () => { const user = new User({ email: 'one@example.com', name: 'One' }); await user.save(); }); ``` -------------------------------- ### Run Release workflow from main Source: https://github.com/avajs/ava/blob/main/maintaining.md Initiate the release process from the 'main' branch. This requires specifying the commit SHA and the desired npm version increment. CI status checks are performed unless explicitly skipped. ```bash Run workflow Set ref to the commit SHA that should be released (must be HEAD of `main`). Set new version to the desired `npm version` increment (e.g. `patch`, `minor`, `major`, or an explicit version like `1.2.3`). Leave skip CI status check unchecked unless you have a specific reason. ``` -------------------------------- ### Import Required Libraries Source: https://github.com/avajs/ava/blob/main/docs/recipes/endpoint-testing-with-mongoose.md Import AVA, SuperTest, MongoDB Memory Server, Mongoose, and your application server and models. ```javascript // Libraries required for testing import test from 'ava'; import request from 'supertest'; import {MongoMemoryServer} from 'mongodb-memory-server'; import mongoose from 'mongoose'; // Your server and models import app from '../server'; import User from '../models/User'; ``` -------------------------------- ### Running AVA Tests Source: https://github.com/avajs/ava/blob/main/docs/recipes/testing-with-selenium-webdriverjs.md Execute AVA tests from the command line using npx. ```bash npx ava ``` -------------------------------- ### Test Page Title with Puppeteer Source: https://github.com/avajs/ava/blob/main/docs/recipes/puppeteer.md Verify that the page title includes a specific string using Puppeteer. This test requires the `withPage` helper for browser and page setup. ```javascript import test from 'ava'; import withPage from './_withPage.js'; const url = 'https://google.com'; test('page title should contain "Google"', withPage, async (t, page) => { await page.goto(url); t.true((await page.title()).includes('Google')); }); ``` -------------------------------- ### Running AVA via npm test Source: https://github.com/avajs/ava/blob/main/docs/05-command-line.md Explains how to pass arguments to AVA when using the 'npm test' command. Flags require the '--' separator. ```console When using `npm test`, you can pass positional arguments directly `npm test test2.js`, but flags needs to be passed like `npm test -- --verbose`. ``` -------------------------------- ### Enable TAP reporter and pipe output Source: https://github.com/avajs/ava/blob/main/docs/05-command-line.md Use the `--tap` flag to enable the TAP output format, which can be piped to other TAP-compatible reporters like `tap-nyan`. ```bash npx ava --tap | npx tap-nyan ``` -------------------------------- ### AVA CLI Options Source: https://github.com/avajs/ava/blob/main/docs/05-command-line.md Details the available command-line options for AVA, such as controlling output color, specifying config files, setting concurrency, and enabling watch mode. ```console Options: --version Show version number [boolean] --color Force color output [boolean] --config Specific JavaScript file for AVA to read its config from, instead of using package.json or ava.config.* files --help Show help [boolean] -c, --concurrency Max number of test files running at the same time (default: CPU cores) [number] --fail-fast Stop after first test failure [boolean] -m, --match Only run tests with matching title (can be repeated) [string] --no-worker-threads Don't use worker threads [boolean] --node-arguments Additional Node.js arguments for launching worker processes (specify as a single string) [string] -s, --serial Run tests serially [boolean] -t, --tap Generate TAP output [boolean] -T, --timeout Set global timeout (milliseconds or human-readable, e.g. 10s, 2m) [string] -u, --update-snapshots Update snapshots [boolean] -v, --verbose Enable verbose output (default) [boolean] -w, --watch Re-run tests when files change [boolean] ``` -------------------------------- ### Example tests for matching titles Source: https://github.com/avajs/ava/blob/main/docs/05-command-line.md This JavaScript code demonstrates test cases that can be filtered using the `--match` flag. Only tests with explicit titles are affected by the `--match` flag. ```javascript test('foo will run', t => { t.pass(); }); test('moo will also run', t => { t.pass(); }); test.only('boo will run but not exclusively', t => { t.pass(); }); ``` -------------------------------- ### VS Code Launch Configuration for Yarn PnP Source: https://github.com/avajs/ava/blob/main/docs/recipes/debugging-with-vscode.md This configuration is for projects using Yarn's Plug'n'Play, which doesn't create a node_modules folder. It uses 'yarn run ava' to execute tests. ```json { "type": "node", "request": "launch", "name": "Debug AVA test file", "runtimeExecutable": "yarn", "runtimeArgs": ["run", "ava"], "args": ["${file}"], "outputCapture": "std", "console": "integratedTerminal", // optional "skipFiles": [ "/**/*.js" ] } ``` -------------------------------- ### Run AVA Tests Source: https://github.com/avajs/ava/blob/main/readme.md Execute your tests using the npm test script. Alternatively, use npx ava. ```console npm test ``` ```console npx ava ``` -------------------------------- ### Set individual test timeout with a message Source: https://github.com/avajs/ava/blob/main/docs/07-test-timeouts.md Provide an optional message to `t.timeout(ms, message)` to explain the reason for the timeout. This is helpful for tests dependent on external setup that might not complete in time. ```javascript test('foo', t => { t.timeout(100, 'make sure database has started'); // 100 milliseconds // Write your assertions here }); ``` -------------------------------- ### Configure AVA in package.json Source: https://github.com/avajs/ava/blob/main/docs/06-configuration.md Set AVA options within the `ava` section of your `package.json` file. This allows for project-wide default configurations. ```json { "ava": { "files": [ "test/**/*", "!test/exclude-files-in-this-directory", "!**/exclude-files-with-this-name.*" ], "match": [ "*oo", "!foo" ], "concurrency": 5, "failFast": true, "failWithoutAssertions": false, "environmentVariables": { "MY_ENVIRONMENT_VARIABLE": "some value" }, "verbose": true, "require": [ "./my-helper-module.js" ], "nodeArguments": [ "--trace-deprecation", "--napi-modules" ] } } ``` -------------------------------- ### Test POST Endpoint with SuperTest and Database Verification Source: https://github.com/avajs/ava/blob/main/docs/recipes/endpoint-testing-with-mongoose.md Send a POST request to create a new user, assert the response, and verify the user was successfully created in the database. ```javascript test.serial('litmus create user', async t => { const {app} = t.context; const res = await request(app) .post('/litmus') .send({ email: 'new@example.com', name: 'New name' }); t is(res.status, 200); t is(res.body.name, 'New name'); // Verify that user is created in DB const newUser = await User.findOne({email: 'new@example.com'}); t is(newUser.name, 'New name'); }); ``` -------------------------------- ### AVA TypeScript Macro with Type Inference Source: https://github.com/avajs/ava/blob/main/docs/recipes/typescript.md Utilize AVA's `test.macro()` helper for enhanced type inference when defining reusable test logic. This example shows a macro that evaluates an expression. ```typescript import test from 'ava'; const macro = test.macro((t, input: string, expected: number) => { tt.is(eval(input), expected); }); test('title', macro, '3 * 3', 9); ``` -------------------------------- ### VS Code Launch Configuration for Precompiled AVA Tests Source: https://github.com/avajs/ava/blob/main/docs/recipes/debugging-with-vscode.md Adapt this configuration when your test files are compiled into a different directory (e.g., 'build'). It uses a wildcard to locate the compiled test files based on the currently open file. ```json { "type": "node", "request": "launch", "name": "Debug AVA test file", "program": "${workspaceFolder}/node_modules/ava/entrypoints/cli.js", "args": [ "build/**/${fileBasenameNoExtension}.*" ], "outputCapture": "std", "console": "integratedTerminal", // optional "skipFiles": [ "/**/*.js" ] } ``` -------------------------------- ### Define Before, After, and Each Hooks Source: https://github.com/avajs/ava/blob/main/docs/01-writing-tests.md Register hooks to run before/after tests or before/after each test. Use `.always()` for guaranteed cleanup. Hooks execute in a specific order: `.before()` before `.beforeEach()`, and `.afterEach()` before `.after()`. Within categories, they run in definition order. ```javascript test.before(t => { // This runs before all tests }); test.before(t => { // This runs concurrently with the above }); test.serial.before(t => { // This runs after the above }); test.serial.before(t => { // This too runs after the above, and before tests }); test.after('cleanup', t => { // This runs after all tests }); test.after.always('guaranteed cleanup', t => { // This will always run, regardless of earlier failures }); test.beforeEach(t => { // This runs before each test }); test.afterEach(t => { // This runs after each test }); test.afterEach.always(t => { // This runs after each test and other test hooks, even if they failed }); test('title', t => { // Regular test }); ``` -------------------------------- ### Configure Node.js Debugging in WebStorm Source: https://github.com/avajs/ava/blob/main/docs/recipes/debugging-with-webstorm.md Specify the path to AVA's executable and pass CLI/Node.js flags for debugging. Use `node_modules/.bin/ava` on macOS/Linux or `node_modules/.bin/ava.cmd` on Windows. Pass `--inspect-brk` in Node parameters to enable the inspector. ```json { "name": "awesome-package", "scripts": { "test": "ava" }, "devDependencies": { "ava": "^1.0.0" } } ``` -------------------------------- ### Run Release workflow from existing tag Source: https://github.com/avajs/ava/blob/main/maintaining.md Trigger the release process when a version tag already exists on the 'main' branch. The 'new version' parameter should be left empty. ```bash Run workflow Set ref to the existing tag (e.g. `v1.2.3`). Leave new version empty. ``` -------------------------------- ### Run self-hosted tests Source: https://github.com/avajs/ava/blob/main/maintaining.md Execute self-hosted tests for a specific file using this command. ```bash npx test-ava test/{file}.js ``` -------------------------------- ### Initialize Shared Worker Factory Source: https://github.com/avajs/ava/blob/main/docs/recipes/shared-workers.md The default export must be a factory method that negotiates a protocol. Call `main.ready()` when initialization is complete to make the worker available. ```javascript export default ({negotiateProtocol}) => { const main = negotiateProtocol(['ava-4']); } ``` -------------------------------- ### AVA CLI Commands Source: https://github.com/avajs/ava/blob/main/docs/05-command-line.md Lists the primary commands available in the AVA CLI: running tests, debugging, and resetting the cache. Use these to control AVA's execution. ```console ava [...] ava debug [...] ava reset-cache ``` -------------------------------- ### Enable Watch Mode Source: https://github.com/avajs/ava/blob/main/docs/recipes/watch-mode.md Run Ava in watch mode using the --watch or -w flags. Integrated debugging and the TAP reporter are unavailable in this mode. ```bash npx ava --watch ``` -------------------------------- ### Import Dependencies for AVA Tests Source: https://github.com/avajs/ava/blob/main/docs/recipes/testing-with-selenium-webdriverjs.md Import necessary modules from AVA, selenium-webdriver, and chromedriver for your test files. ```javascript import test from 'ava'; import {Builder, By, Key, until} from 'selenium-webdriver'; import 'chromedriver'; ``` -------------------------------- ### Run multiple tests by line numbers and ranges Source: https://github.com/avajs/ava/blob/main/docs/05-command-line.md Execute specific tests by providing a comma-separated list of line numbers and ranges. Line numbers are 1-based. ```bash npx ava test.js:2,9 ``` ```bash npx ava test.js:4-7 ``` ```bash npx ava test.js:4,9-12 ``` -------------------------------- ### AVA CLI Command Descriptions Source: https://github.com/avajs/ava/blob/main/docs/05-command-line.md Provides descriptions for AVA's core commands: running tests, activating the Node.js inspector for debugging, and clearing AVA's cache. ```console Commands: ava [...] Run tests [default] ava debug [...] Activate Node.js inspector and run a single test file ava reset-cache Delete any temporary files and state kept by AVA, then exit ``` -------------------------------- ### Run with --break Option Source: https://github.com/avajs/ava/blob/main/docs/recipes/debugging-with-chrome-devtools.md Enable the `--break` option to pause execution right before the test file is loaded, ensuring the DevTools hit a breakpoint immediately. ```bash npx ava debug --break test.js ``` -------------------------------- ### VS Code Launch Configuration for Serial AVA Debugging Source: https://github.com/avajs/ava/blob/main/docs/recipes/debugging-with-vscode.md Use this configuration to ensure AVA runs tests serially, which can simplify debugging. Add the '--serial' argument to the 'args' array. ```json { "type": "node", "request": "launch", "name": "Debug AVA test file", "program": "${workspaceFolder}/node_modules/ava/entrypoints/cli.js", "args": [ "--serial", "${file}" ], "outputCapture": "std", "console": "integratedTerminal", // optional "skipFiles": [ "/**/*.js" ] } ``` -------------------------------- ### VS Code Launch Configuration for AVA Source: https://github.com/avajs/ava/blob/main/docs/recipes/debugging-with-vscode.md Use this configuration to debug individual AVA test files directly within VS Code. Ensure the 'program' path points to the AVA CLI entry point. ```json { "type": "node", "request": "launch", "name": "Debug AVA test file", "program": "${workspaceFolder}/node_modules/ava/entrypoints/cli.js", "args": [ "${file}" ], "outputCapture": "std", "console": "integratedTerminal", // optional "skipFiles": [ "/**/*.js" ] } ``` -------------------------------- ### Passing Arguments Directly Source: https://github.com/avajs/ava/blob/main/docs/recipes/passing-arguments-to-your-test-files.md Pass arguments to your test file by separating AVA's arguments from your own with `--`. The arguments are then available in `process.argv`. ```javascript import test from 'ava'; test('argv', t => { t.deepEqual(process.argv.slice(2), ['--hello', 'world']); }); ``` ```bash $ npx ava -- --hello world ``` -------------------------------- ### Configure npm test script Source: https://github.com/avajs/ava/blob/main/docs/recipes/code-coverage.md Configure your package.json to run AVA tests through c8 for code coverage. ```json { "scripts": { "test": "c8 ava" } } ``` -------------------------------- ### Configure Snapshot Directory Source: https://github.com/avajs/ava/blob/main/docs/04-snapshot-testing.md Specify a custom directory for storing snapshot files within your AVA configuration in package.json. ```json { "ava": { "snapshotDir": "custom-directory" } } ``` -------------------------------- ### Configure timeouts using CLI options Source: https://github.com/avajs/ava/blob/main/docs/07-test-timeouts.md Set test timeouts using the `--timeout` command-line option. Timeouts can be specified in seconds (s), minutes (m), or milliseconds. ```bash npx ava --timeout=10s # 10 seconds ``` ```bash npx ava --timeout=2m # 2 minutes ``` ```bash npx ava --timeout=100 # 100 milliseconds ``` -------------------------------- ### AVA Configuration with Factory Function Source: https://github.com/avajs/ava/blob/main/docs/06-configuration.md A factory function can be exported from `ava.config.js` to dynamically generate the configuration object. This function receives `projectDir` as an argument. ```javascript export default function factory() { return { require: ['./_my-test-helper.js'] }; }; ``` ```javascript export default ({projectDir}) => { if (projectDir === '/Users/username/projects/my-project') { return { // Config A }; } return { // Config B }; }; ``` -------------------------------- ### Automated Reporter Log Update for All Supported Node.js Versions Source: https://github.com/avajs/ava/blob/main/test-tap/reporters/readme.md This command uses `jq` to parse Node.js versions from `package.json` and then uses `xargs` with Volta to run the reporter log update for each version. This automates the process for all supported Node.js versions. ```bash jq { const data = await fetch(); t.is(data, 'foo'); }); ``` -------------------------------- ### Run a single test by line number Source: https://github.com/avajs/ava/blob/main/docs/05-command-line.md Specify a test file and a line number to execute only that specific test. Any line number within the test's definition is valid. ```bash npx ava test.js:2 ``` -------------------------------- ### Run a specific test file with bail Source: https://github.com/avajs/ava/blob/main/maintaining.md Use this command to run a single test file and stop immediately upon the first failure. This is particularly useful for debugging. ```bash npx tap test-tap/fork.js --bail ``` -------------------------------- ### Customize Host and Port for Inspector Source: https://github.com/avajs/ava/blob/main/docs/recipes/debugging-with-chrome-devtools.md Customize the host and port for the inspector when running AVA in debug mode. You will need to add a corresponding connection in the DevTools. ```bash npx ava debug --host 0.0.0.0 --port 9230 test.js ``` -------------------------------- ### Basic Ava Test Structure Source: https://github.com/avajs/ava/blob/main/docs/02-execution-context.md A fundamental Ava test demonstrating the `t` context. Import `test` from 'ava' and use the `t` object within the test callback to perform assertions. ```javascript import test from 'ava'; test('my passing test', t => { t.pass(); }); ``` -------------------------------- ### .notRegex(contents, regex, message?) Source: https://github.com/avajs/ava/blob/main/docs/03-assertions.md Asserts that `contents` does not match the provided `regex`. ```APIDOC ## .notRegex(contents, regex, message?) ### Description Assert that `contents` does not match `regex`. ``` -------------------------------- ### Configure Coverage Reporting for Vue Files Source: https://github.com/avajs/ava/blob/main/docs/recipes/vue.md To include `.vue` files in coverage reports, add the `.vue` extension to the `c8` configuration. This ensures that Vue component code is instrumented and analyzed. ```json { "c8": { "extension": [ ".js", ".vue" ] } } ``` -------------------------------- ### AVA CLI Positional Arguments Source: https://github.com/avajs/ava/blob/main/docs/05-command-line.md Explains the 'pattern' positional argument, which allows specifying which test files to run using glob patterns, directories, or specific file paths with line numbers. ```console Positionals: pattern Select which test files to run. Leave empty if you want AVA to run all test files as per your configuration. Accepts glob patterns, directories that (recursively) contain test files, and file paths optionally suffixed with a colon and comma-separated numbers and/or ranges identifying the 1-based line(s) of specific tests to run [string] ``` -------------------------------- ### Enabling Experimental Features in AVA Source: https://github.com/avajs/ava/blob/main/docs/06-configuration.md Opt into experimental AVA features by enabling them in the `nonSemVerExperiments` configuration object within `ava.config.js`. ```javascript export default { nonSemVerExperiments: { feature: true } }; ``` -------------------------------- ### Run tests matching the exact title 'foo' Source: https://github.com/avajs/ava/blob/main/docs/05-command-line.md Use the `--match` flag with a pattern to filter tests by their exact titles, ignoring case. Patterns are case-insensitive. ```bash npx ava --match='foo' ``` -------------------------------- ### Use `.like()` for partial deep equality Source: https://github.com/avajs/ava/blob/main/docs/03-assertions.md Use `.like()` when `actual` does not need to have the same enumerable properties as `selector`. Ava derives a comparable value from `actual` based on the enumerable shape of `selector`. ```javascript t.like({ map: new Map([['foo', 'bar']]), nested: { baz: 'thud', qux: 'quux' } }, { map: new Map([['foo', 'bar']]), nested: { baz: 'thud', } }) ``` ```javascript t.like([1, 2, 3, 4], [1, , 3]) ``` -------------------------------- ### Pass additional arguments to Node.js worker processes Source: https://github.com/avajs/ava/blob/main/docs/05-command-line.md Use the `--node-arguments` flag to specify extra arguments for launching AVA's worker processes. Ensure only trusted values are passed. ```bash npx ava --node-arguments="--throw-deprecation --zero-fill-buffers" ``` -------------------------------- ### Define Reusable Test Logic with test.macro() Source: https://github.com/avajs/ava/blob/main/docs/01-writing-tests.md Utilize the `test.macro()` helper for a more structured approach to creating reusable test macros. This method accepts a function that receives the test instance, input, and expected values. ```javascript import test from 'ava'; const macro = test.macro((t, input, expected) => { t.is(eval(input), expected); }); test('title', macro, '3 * 3', 9); ``` -------------------------------- ### AVA TypeScript Configuration Source: https://github.com/avajs/ava/blob/main/docs/recipes/typescript.md Configure AVA to recognize TypeScript files and use the 'tsimp' loader for on-the-fly compilation. Ensure your TypeScript configuration outputs ES modules. ```json { "ava": { "extensions": ["ts"], "nodeArguments": [ "--import=tsimp" ] } } ``` -------------------------------- ### Promisifying Callbacks with `util.promisify` Source: https://github.com/avajs/ava/blob/main/docs/08-common-pitfalls.md If you are using callback-based asynchronous functions, promisify them using `util.promisify` and then use `async/await` for better error handling and test attribution. ```javascript import {promisify} from 'util'; test('fetches foo', async t => { const data = await promisify(fetch)(); t.is(data, 'foo'); }); ``` -------------------------------- ### Run tests with line numbers across multiple files Source: https://github.com/avajs/ava/blob/main/docs/05-command-line.md Specify line numbers for tests in different files. If the same file is listed multiple times, its line numbers are merged. ```bash npx ava test.js:3 test2.js:4,7-9 ``` -------------------------------- ### Compile TypeScript with AVA Source: https://github.com/avajs/ava/blob/main/test/line-numbers/fixtures/README.md Use this command to compile TypeScript files for AVA, ensuring source maps and specific module settings are applied. This command is useful for setting up the build process for AVA projects. ```console npx tsc line-numbers.ts --outDir . --sourceMap --module es2020 --moduleResolution node --removeComments ```