This stack illustrates the article API Testing with Vitest.
A basic set of packages to test API with TypeScript:
- Vitest — testing framework;
- Node.js
fetch()
as HTTP client; - Zod — schema validation;
- date-fns — modern date utility library;
- Prettier — code formatter;
- ESLint – code linter.
Example API for testing: APOD NASA API.
You have to have Node.js >= 21 in order to use fetch()
.
- Clone repository;
- Install dependencies:
npm install
- Run tests:
npm run test
- Different tested host could be passed to tests through
.env
variable (it can be useful for testing different environments):
HOST=https://api.nasa.gov npm test
- Individual API key could be passed to tests through
.env
variable (otherwise, it will be usedDEMO_KEY
value):
API_KEY={api_key} npm test
- Run a single test or tests that match a specific filename (for example
epic.test.ts
):
npm test epic
- Run tests in UI watch mode:
npm run test:ui
Tests replicate API tests on Jest from this repository:
apod.test.ts
— test with JSON schema validation;epic.test.ts
— test has a loop through array for checking elements with Chai assertion;insight-weather.test.ts
— test will be conditionally skipped in an inappropriate environment.
Concerns of the stack: Zod is highly inconvenient as JSON schema validator in case of dynamic keys inside an object with other typed keys.