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 — date utility library
- Prettier — code formatter
- ESLint — code linter
Example API for testing: 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
.envvariable (it can be useful for testing different environments):
HOST=https://api.nasa.gov npm test
- Individual API key could be passed to tests through
.envvariable (otherwise, it will be usedDEMO_KEYvalue):
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 validationepic.test.ts— test has a loop through array for checking elements with Chai assertioninsight-weather.test.ts— test will be conditionally skipped in an inappropriate environment
Concerns of the stack: Zod is an inconvenient JSON schema validator when there are dynamic keys inside an object with other typed keys.