Disclaimer: I consider the stack below to be outdated. Contemporary API testing stack on Vitest + Node.js fetch()
can be found here.
A basic set of packages to test API with TypeScript and HTTP client:
- Jest — testing framework;
- Jest-extended — additional Jest matchers;
- Got — library for HTTP requests;
- Ajv — JSON schema validator;
- date-fns — library for dates;
- Prettier — code formatter;
- ESLint – code linter.
Example API for testing: APOD NASA API.
- 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
apod.test.ts
— test with JSON schema validation;epic.test.ts
— test has a loop through array for checking elements with jest-extended assert;insight-weather.test.ts
— test will be conditionally skipped in an inappropriate environment.
There were a lot of problems with the last versions of configuration Got and Jest and TypeScript:
- Got from the 12 version requires only ESM and requires:
"module": "node16",
"moduleResolution": "node16"
in tsconfig file (as it told in the last release notes);
- Due to the setting above, if you import .ts files inside your .ts files (like I do to import utils' functions inside tests), you need to add:
"noEmit": true,
"emitDeclarationOnly": false,
"allowImportingTsExtensions": true
in tsconfig file too;
- Then you need to add
"type": "module"
inpackage.json
for usingimport
in .ts files; - But with this setting, the whole Jest stops working and requires a different launch method, as told in Jest's documentation about experimental support for ECMAScript Modules:
node --experimental-vm-modules ./node_modules/.bin/jest
- And even this does not work without ts-jest package and jest.config.ts settings:
transform: {'^.+\\.(ts|tsx)?$': ['ts-jest', { useESM: true }]},
extensionsToTreatAsEsm: ['.ts']
- Last but not least, changing filetype from
jest.config.js
tojest.config.ts
leads to more configuration changes (I don't remember how)…
I would recommend using Axios as an HTTP client to make setup process much easier (if you do not need specific features of Got). But in this repository, I continue to use Got, because this is the way.
Example of Jest + Axios can be found here.