Files
directus/docs/contributing/tests.md
Connor 92621429ee Linting and Formatting Upgrade (#18892)
* add docs to eslint

* update prettier ignore

* fix vitepress linting

* eslint ignore fixes

* prettier run

* update prettier ignore

* fix formatting

* enable linting of markdown files

* revert format command change

* fix irregular whitespace

* update dictionary

* (Changelog) Create four-boxes-shake.md

* Rework ESLint / Prettier setup

- Disable js/ts/vue files for Prettier to ensure linting/formatting is
  only happening via ESLint
- Rework formatting of code blocks in md files
  - Disable formatting of code blocks in md files under '/docs' by Prettier
  - Instead use "eslint-plugin-markdown" to format & __lint__ js*/ts*/vue such code blocks
  - Replace unmaintained "eslint-plugin-md" plugin by official "eslint-plugin-markdown" plugin
  - I'll check whether we can use this to format other code blocks
    (json, html, ...) as well
- Restructure, clean-up and apply some fixes to the ESLint config
  (Note: Not ready for flat config yet since not supported by
  vscode-eslint)
- Enable cache for ESLint / Prettier in scripts
- Clean-up ignore file
  - Explicit folder declaration (.../)
  - Don't ignore all 'extensions' folders in ESLint (only
    '/api/extensions/')
  - Enable formatting in '/.github' folder

* Fix all formatting issues with Prettier

* Update md files under /docs/.typedocs

* Fix lint issues in vue/js files

* ESLint / Prettier config revision v2

Enable Prettier for md code blocks, but only as warnings since it can
get into the way with Vitepress md extensions like '[!code ...]'
comments

* Remove prettier-ignore comments

* Make spellchecker happy

* Remove changeset

* Revert lint setup for code blocks

There are many cases in the docs where linting / formatting of code
blocks doesn't make
sense:
- Code block is only an excerpt - linter fails
- Code block contains special comments (e.g. markdown extensions) which
  needs to remain at the same place - formatting would break it
- ...

* Apply lint issues / formatting from temp lint setup

* Run formatter

* Fix merge failure

* Simplify & modernize ESLint / Prettier setup

No longer run Prettier via ESLint. Nowadays, this is the recommended
setup. There's no real need to run it this way, it's just an additional
layer.

Add VS Code settings to make the work with the new setup easier.

* Remove unused eslint disable directives

* Make editorconfig more useful

* Fix formatting issues reported by editorconfig

* Format files with Prettier

* Enable formatting of source translations file

* Format source translations file

* Remove unnecessary console error

* Remove unnecessary line

* Only ignore md files under .changeset

* Add CI reporter for Prettier

* Fail job on wrongly formatted files

* Fix format

* Test Prettier action on changed/added file

* Use simple CI format check for now & no cache

* Revert "Test Prettier action on changed/added file"

This reverts commit 4f7d8826ad.

* Introduce code blocks check for docs

* Fix code block issues

* Ignore auto-generated packages dir

* Fix comment position

* Also lint `/app/.storybook`

* Reformat modified files

---------

Co-authored-by: Pascal Jufer <pascal-jufer@bluewin.ch>
Co-authored-by: Rijk van Zanten <rijkvanzanten@me.com>
2023-06-29 11:54:01 +02:00

4.9 KiB

Tests

Tests ensure that the platform continues to work as intended when the existing codebase is modified.

The current test strategy for Directus consists of Blackbox Tests testing the overall functionality of the platform as well as Unit Tests testing individual parts of the codebase.

Running Unit Tests

Use the following command to perform unit tests in all packages:

pnpm --workspace-root test

Use one of the following commands to perform more specific actions with unit tests (mix and match as desired):

# Run tests for a specific package (for example only in the API / App package)
pnpm --filter api test
pnpm --filter app test

# Start tests in watch mode
pnpm --filter api test -- --watch

# Enable coverage report
pnpm --filter api test -- --coverage

# Run specific test files using a filter pattern
pnpm --filter api test -- app.test.ts
pnpm --filter api test -- utils

:::tip Relative Commands

If you are already in a directory of a specific package, you may omit the --filter flag in pnpm commands since the commands will be executed relative to the current directory.

# Run API tests, from within the "/api" directory
pnpm test

:::

Running Blackbox Tests

Install Docker and ensure that the service is up and running.

Run the following commands to start the blackbox tests:

# Ensure that you are testing against the lastest state of the codebase
pnpm --workspace-root build

# Clean up in case you ran the tests before
pnpm --filter tests-blackbox exec docker compose down --volumes
# Start the containers required for the tests
pnpm --filter tests-blackbox exec docker compose up --detach --wait

# Run the tests
pnpm --workspace-root test:blackbox

Subsequent test runs can be issued with the following command, if only modifications to the blackbox tests themselves have been made:

pnpm --filter tests-blackbox test

Testing Specific Database Vendors

Provide a CSV of database vendors via the TEST_DB environment variable to target only a specific subset:

# Example targeting multiple vendors
TEST_DB=cockroachdb,postgres pnpm --workspace-root test:blackbox

# Example targeting a single vendor
TEST_DB=sqlite3 pnpm --workspace-root test:blackbox

Using an Existing Directus Instance

Normally, the test suite will spin up a fresh copy of the Directus API built from the current state of the codebase. To use an already running instance of Directus instead, enable the TEST_LOCAL flag:

TEST_DB=cockroachdb TEST_LOCAL=true pnpm --workspace-root test:blackbox

Note: The tests expect the instance running at localhost:8055. Make sure to connect the instance to the test database container found in the tests-blackbox/docker-compose.yml file.

Writing Unit Tests

Unit Tests are written throughout the codebase in a vite native unit test framework called Vitest.

Example

/directus/api/src/utils/get-date-formatted.test.ts
import { afterEach, beforeEach, expect, test, vi } from 'vitest';

import { getDateFormatted } from './get-date-formatted.js';

beforeEach(() => {
	vi.useFakeTimers();
});

afterEach(() => {
	vi.useRealTimers();
});

function getUtcDateForString(date: string) {
	const now = new Date(date);

	// account for timezone difference depending on the machine where this test is ran
	const timezoneOffsetInMinutes = now.getTimezoneOffset();
	const timezoneOffsetInMilliseconds = timezoneOffsetInMinutes * 60 * 1000;
	const nowUTC = new Date(now.valueOf() + timezoneOffsetInMilliseconds);

	return nowUTC;
}

test.each([
	{ utc: '2023-01-01T01:23:45.678Z', expected: '20230101-12345' },
	{ utc: '2023-01-11T01:23:45.678Z', expected: '20230111-12345' },
	{ utc: '2023-11-01T01:23:45.678Z', expected: '20231101-12345' },
	{ utc: '2023-11-11T12:34:56.789Z', expected: '20231111-123456' },
	{ utc: '2023-06-01T01:23:45.678Z', expected: '20230601-12345' },
	{ utc: '2023-06-11T12:34:56.789Z', expected: '20230611-123456' },
])('should format $utc into "$expected"', ({ utc, expected }) => {
	const nowUTC = getUtcDateForString(utc);

	vi.setSystemTime(nowUTC);

	expect(getDateFormatted()).toBe(expected);
});

Writing Blackbox Tests

Example

/directus/tests/blackbox/routes/server/ping.test.ts
import { getUrl } from '@common/config';
import request from 'supertest';
import vendors from '@common/get-dbs-to-test';
import { requestGraphQL } from '@common/transport';

describe('/server', () => {
	describe('GET /ping', () => {
		it.each(vendors)('%s', async (vendor) => {
			// Action
			const response = await request(getUrl(vendor))
				.get('/server/ping')
				.expect('Content-Type', /text\/html/)
				.expect(200);

			const gqlResponse = await requestGraphQL(getUrl(vendor), true, null, {
				query: {
					server_ping: true,
				},
			});

			// Assert
			expect(response.text).toBe('pong');
			expect(gqlResponse.body.data.server_ping).toBe('pong');
		});
	});
});