api-test-kit
v1.0.2
Published
API Testing Kit
Downloads
39
Maintainers
Readme
API TEST KIT
Overview
API TEST KIT is a powerful tool designed to simplify API testing. This package provides features for generating REST API clients from OpenAPI JSON/YAML files, custom-built API assertions for response validation, and built-in logging for all requests and responses.
Features
- Generates REST API Client using OpenAPI Specification JSON/YAML files.
- Supports Playwright, Axios, and SuperTest as HTTP client libraries.
- Custom-built assertions for API response validation.
- Built-in logging to capture request and response details.
Installation
npm install api-test-kitUsage
Step 1: Generate REST API Client
The API Client Generator CLI tool generates API client code from an OpenAPI JSON specification, allowing customization of various aspects like HTTP library selection, naming conventions, and output directory.
CLI Command
npx apiBuilder --helpCLI Options
Usage: apiBuilder [options]
Options:
--json <path> Path to the OpenAPI JSON specification file
--serviceName <name> Custom name for the generated API client (e.g., MyAPIClient)
-l, --libraryName <Playwright/Axios/SuperTest> HTTP client library to use for API requests (default: Axios)
--classNameKey <key> Determines the class name for API endpoints (default: "tags")
--methodNameKey <key> Determines the method name for API operations (default: "operationId")
-f, --featureName <featureName> Generate the API client for a specific feature or endpoint
-o, --output <path> Output directory where the generated API client files will be saved
-h, --help Display help for commandExample
Generating a Covid API service client from https://covid-api.com/api/:
npx apiBuilder --json https://covid-api.com/api/docs/api-docs.json --serviceName Covid --output covid-apiOutput Directory Structure
covid-api
├── Covid.ts
├── CovidApiManager.ts
└── endpoints
├── RegionApi.ts
├── ReportApi.ts
└── schema.jsonStep 2: Consuming the Generated API Client
Example API Request
const covidClient = new CovidClient('https://covid-api.com');
covidClient.loggingManager.enable();
const response = await covidClient.region.regions({
headers: {
'X-CSRF-TOKEN': '',
},
params: {
per_page: 20,
},
});
await response.verifyResponse({
status: 200,
statusText: 'OK',
'time[?]less_than': 5000,
data: {
current_page: 1,
data: [
{ iso: 'AUS', name: 'Australia' },
{ iso: 'USA', name: 'US' },
],
},
schema: 'Region-regions-200',
});Request Data - RequestData
{
// `timeout` specifies the number of milliseconds before the request times out.
timeout: number, // default is `30000`
// `headers` are custom headers to be sent
headers: { [key: string]: string},
// `params` are the URL parameters to be sent with the request
params: { [key: string]: string | number | boolean } | URLSearchParams,
// `data` is the data to be sent as the request body
data: Serializable,
// form data to be sent with the request
formData: { [key: string]: string | number | boolean } | FormData
}Response Data - ResponseData
{
// `url` used when sending the request
url: string,
// `method` used for the request
method: string,
// `time` in ms took to process the request
time: number,
// `status` is the HTTP status code from the server response
status: number,
// `statusText` is the HTTP status message from the server response
statusText: string,
ok: boolean,
// An object with all the response HTTP headers associated with this response.
headers: { [key: string]: string},
// Returns the JSON representation of response body.
json(): Promise<Serializable>,
// Returns the text representation of response body.
text(): Promise<string>,
// Returns the request and response log
log(): string[],
// Verifies the response received from the server with the expected response
verifyResponse(expectedResponse: {
status?: number;
statusText?: string;
time?: number;
headers?: { [key: string]: string };
data?: { [key: string]: any };
schema?: string;
[key: string]: any;
}): Promise<boolean | void>
}Available Methods
Logging
- Enable logging: Logging once enabled at the client it cannot be enabled again. The log file is generated with the current datetime.
covidClient.loggingManager.enable();- Custom logging configuration:
covidClient.loggingManager.enable({ level: 'info', filepath: './logs', filename: 'api-log.txt' });- Disable logging:
covidClient.loggingManager.disable();- Log a message:
covidClient.loggingManager.log('Custom log message');Headers Management
- Add header at session level:
covidClient.headerManager.add({ Authorization: 'Bearer token' });- Remove a header:
covidClient.headerManager.remove('Authorization');- Get session-level headers:
covidClient.headerManager.get();API Statistics
covidClient.apiManager.apiStats();HTML API Request and Respons Log
Ensure to disable the logging before generating the HTML report
await covidClient.loggingManager.disable();
generateHtmlReport(covidClient.loggingManager.getLogFile());Assertions for API response validation
await response.verifyResponse({
status: 200,
statusText: 'OK',
'time[?]less_than': 5000,
data: {
'current_page[?]defined': 1,
'data[?]contains': [
{ iso: 'AUS', name: 'Australia' },
{ iso: 'USA', name: 'US' },
],
},
schema: 'Region-regions-200',
});String Comparison Operators
| Operator | Description | Example |
| -------------- | ----------------------------- | ------------------------------------- |
| equal_to | Exact string match (Default) | 'city[?]equal_to': 'Sydney' |
| ignore_case | Case-insensitive string match | 'city[?]ignore_case': 'SYDney' |
| not_equal_to | String inequality | 'city[?]not_equal_to': 'Melbourne' |
| contains | Substring check | 'city[?]contains': 'Syd' |
| not_contains | Substring absence | 'city[?]not_contains': 'Mel' |
| match | Regular expression match | 'city[?]match': 'Syd.*' |
| defined | Field exists | 'city[?]defined': 'Sydney' |
| not_defined | Field absent | 'city_name[?]not_defined': 'Sydney' |
Number Comparison Operators
| Operator | Description | Example |
| ----------------------- | -------------------------- | --------------------------------- |
| equal_to | Numeric equality (Default) | 'id[?]equal_to': 1234 |
| not_equal_to | Numeric inequality | 'id[?]not_equal_to': 4567 |
| less_than | Less than | 'id[?]less_than': 10000 |
| less_than_equal_to | Less than equal to | 'id[?]less_than_equal_to': 9999 |
| greater_than | Greater than | 'id[?]greater_than': 0 |
| greater_than_equal_to | Greater than equal to | 'id[?]greater_than_equal_to': 1 |
| is_between | Range check | 'id[?]is_between': '1 to 9999' |
| defined | Field exists | 'id[?]defined': 1234 |
| not_defined | Field absent | 'id[?]not_defined': 1234 |
Boolean Comparison Operators
| Operator | Description | Example |
| -------------- | -------------------------- | -------------------------------- |
| equal_to | Boolean equality (Default) | 'status[?]equal_to': true |
| not_equal_to | Boolean inequality | 'status[?]not_equal_to': false |
| defined | Field exists | 'status[?]defined': true |
| not_defined | Field absent | 'status[?]not_defined': true |
List/Array Comparison Operators
| Operator | Description | Example |
| ----------------- | ------------------------------------ | -------------------------------------------------------------- |
| equal_to | Exact array match | 'cities[?]equal_to': ['Sydney', 'Melbourne', 'Perth'] |
| contains | Contains elements in array (Default) | 'cities[?]contains': ['Sydney', 'Melbourne'] |
| contains_once | Contains elements exactly once | 'cities[?]contains_once': ['Sydney', 'Melbourne'] |
| not_contains | Does not contain elements | 'cities[?]not_contains': ['Brisbane', 'Adelaide'] |
| ignore_sequence | Array match irrespective of sequence | 'cities[?]ignore_sequence': ['Melbourne', 'Perth', 'Sydney'] |
| defined | Field exists | 'cities[?]equal_to': [] |
| not_defined | Field absent | 'cities[?]not_defined': [] |
Map/Object Comparison Operators
| Operator | Description | Example |
| ------------- | ------------------------------------------------ | -------------------------------------------------------------------- |
| equal_to | Exact object match | 'data[?]equal_to': { name: 'Trish', city: 'Sydney' , status: true} |
| contains | Contains specified key/value in object (Default) | 'data[?]contains': { name: 'Trish', city: 'Sydney'} |
| defined | Field exists | 'data[?]equal_to': {} |
| not_defined | Field absent | 'data[?]not_defined': {} |
Data Type Comparison Operators
is- Verifies the data type of a fieldAvailable Data Types: 'string', 'number', 'boolean', 'array', 'object', 'array_of_string', 'array_of_number', 'array_of_boolean', 'array_of_object' Example: 'data[?]is': 'object'
Conclusion
API TEST KIT streamlines API testing by offering client generation, assertions, and logging, making it an essential tool for developers working with REST APIs. For further details and advanced configurations, refer to the official documentation.
