OpenAPI Test Templates Generator
OATTS (OpenAPI Test Templates) is a utility designed to generate basic Node.js unit test scaffolding directly from an OpenAPI specification document. Currently at version 1.6.0, it provides both a command-line interface and a module API to automate the creation of boilerplate tests for your API endpoints. The generated tests are structured for the Mocha testing framework and utilize Chakram for API assertions, encouraging developers to maintain a consistent contract between their API specification and its implementation. While providing valuable scaffolding for early and continuous API contract testing, it's important to note that OATTS is described as a 'work in progress' and 'not an officially supported Google product', suggesting a less frequent release cadence and potentially limited long-term support compared to core Google projects. Its primary differentiator is its focus on generating runnable Mocha/Chakram tests specifically for Node.js environments, building on lessons learned from `swagger-test-templates`.
Common errors
-
Error: Cannot find module 'mocha' (or 'chakram')
cause The generated tests require 'mocha' and 'chakram' to run, but these are not direct dependencies of the 'oatts' package itself.fixInstall `mocha` and `chakram` as development dependencies in your project's test environment: `npm install --save-dev mocha chakram`. -
oatts generate: command not found
cause The `oatts` command-line interface (CLI) tool was either not installed globally or is not accessible in your system's PATH.fixInstall the `oatts` CLI globally using `npm install -g oatts`, or execute the command directly using `npx oatts generate ...` if you prefer not to install globally. -
TypeError: oatts.generate is not a function
cause This error typically occurs if `oatts` was imported incorrectly (e.g., attempting a named import when only a CommonJS default export exists) or if the module resolution failed.fixEnsure you are importing the module using the CommonJS `require` syntax: `const oatts = require('oatts');`. Then, call `oatts.generate(...)`. -
Generated tests consistently fail with connection refused errors or unexpected HTTP status codes (e.g., 500, 404).
cause The API server that the generated tests are configured to target is either not running, inaccessible from the test environment, or the `--host` option (or default host) used during test generation does not match the server's actual address.fixStart your API server before running the generated tests. Verify that the `host` option supplied to `oatts.generate` (or the `--host` CLI option) correctly points to your running API's address and port.
Warnings
- gotcha This project is explicitly noted as 'not an officially supported Google product' and 'a work in progress'. Users should be aware this implies potential for limited long-term support, infrequent updates, and the possibility of API changes without strict adherence to semantic versioning guidelines.
- gotcha The unit tests generated by `oatts` are designed to run with the `mocha` testing framework and rely on `chakram` for API assertions. These frameworks are not direct dependencies of `oatts` itself and must be installed separately in your test environment for the generated tests to execute successfully.
- gotcha The official documentation and examples for `oatts` exclusively use CommonJS (`require()`) syntax. While Node.js has robust ESM support, direct native ES Module (`import`) usage for the `oatts` library itself is not explicitly supported and may lead to import resolution errors or unexpected behavior.
- gotcha When providing custom Handlebars templates for test generation, the directory specified must contain exactly four templates with specific predefined names to be correctly recognized by `oatts`. Deviations from this naming convention will result in templates not being applied.
- gotcha Version 1.3.0 of `oatts` included fixes for 'vulnerabilities per GitHub scanning'. While these issues have been addressed in later versions, it indicates that earlier versions (prior to 1.3.0) may have contained security vulnerabilities. Users should prioritize updating.
Install
-
npm install oatts -
yarn add oatts -
pnpm add oatts
Imports
- oatts (module)
import oatts from 'oatts';
const oatts = require('oatts'); - generate (function)
import { generate } from 'oatts';const tests = oatts.generate('/path/to/openapi.yaml', options);
Quickstart
const oatts = require('oatts');
const path = require('path');
const fs = require('fs');
// Create a dummy OpenAPI spec for demonstration
const dummyOpenApiSpecPath = path.join(__dirname, 'dummy-openapi.yaml');
const dummyOpenApiSpecContent = `
openapi: 3.0.0
info:
title: Dummy API
version: 1.0.0
servers:
- url: http://localhost:3000
paths:
/hello:
get:
summary: Greet the user
operationId: getHello
responses:
'200':
description: Successful response
content:
application/json:
schema:
type: object
properties:
message:
type: string
/goodbye/{name}:
parameters:
- name: name
in: path
required: true
schema:
type: string
get:
summary: Bid farewell
operationId: getGoodbye
responses:
'200':
description: Successful farewell
content:
application/json:
schema:
type: object
properties:
farewellMessage:
type: string
`;
fs.writeFileSync(dummyOpenApiSpecPath, dummyOpenApiSpecContent);
// Options for test generation
const options = {
host: 'http://localhost:3000', // Target API host for generated tests
writeTo: path.join(__dirname, 'generated-tests'), // Directory to write tests
// You can specify specific paths: paths: '/hello,/goodbye/{name}'
};
console.log('Generating tests for dummy OpenAPI spec...');
// Generate the tests
oatts.generate(dummyOpenApiSpecPath, options)
.then((generatedFiles) => {
console.log('Tests generated successfully:');
generatedFiles.forEach(file => console.log(`- ${file}`));
console.log(`
To run these tests, you'll need mocha and chakram installed:
npm install --save-dev mocha chakram
Then, start your API server (if applicable) and run:
mocha --recursive ${options.writeTo}`);
})
.catch((error) => {
console.error('Error generating tests:', error);
})
.finally(() => {
// Clean up the dummy spec file and generated test directory
fs.unlinkSync(dummyOpenApiSpecPath);
// Note: Deleting the generated test directory is more complex and left out for quickstart clarity
// You might want to remove this for actual usage to inspect generated files.
});