Skip to content

adequatica/api-testing

Repository files navigation

API Testing with TypeScript, Jest, and Got

Disclaimer: I consider the stack below to be outdated. Contemporary API testing stack on Vitest + Node.js fetch() can be found here.

Stack

A basic set of packages to test API with TypeScript and HTTP client:

Example API for testing: APOD NASA API.

How to Use

  1. Clone repository
  2. Install dependencies: npm install
  3. Run tests: npm run test

CLI Options

  • 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 used DEMO_KEY value):

API_KEY={api_key} npm test

npm test epic

Examples of Test Cases

  • 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.

Story about updating packages (2023-11-23) to the latest versions

There were a lot of problems with the last versions of configuration Got and Jest and TypeScript:

  1. Got from the 12 version requires only ESM and requires:
  2. 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;
  3. Then you need to add "type": "module" in package.json for using import in .ts files;
  4. 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
  5. And even this does not work without ts-jest package and jest.config.ts settings:
    • transform: {'^.+\\.(ts|tsx)?$': ['ts-jest', { useESM: true }]},
    • extensionsToTreatAsEsm: ['.ts']
  6. Last but not least, changing filetype from jest.config.js to jest.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.

About

Testing API with TypeScript, Jest, and Got

Topics

Resources

Stars

Watchers

Forks