Swagger Test Code Generator

1.6.0 · maintenance · verified Tue Apr 21

swagger-test-templates is a Node.js library designed to generate API test code directly from a Swagger 2.0 specification. It currently stands at version 1.6.0, with its most recent listed releases (1.5.0, 1.4.0) indicating ongoing maintenance rather than rapid feature development. The library differentiates itself by allowing users to specify the assertion format (e.g., 'should', 'expect', 'assert') and the HTTP request module (e.g., 'supertest', 'request') for the generated tests. It also includes capabilities for generating load tests and supports custom Handlebars templates for advanced customization of the test output. A key limitation is its exclusive focus on Swagger 2.0, meaning it does not natively support newer OpenAPI 3.x specifications.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize `swagger-test-templates` with a mock Swagger 2.0 spec and configuration, generating test files for specified paths and including basic load test setup.

const stt = require('swagger-test-templates');
const fs = require('fs');

// In a real scenario, replace this with a path to your actual Swagger 2.0 JSON file
const swaggerSpec = {
  "swagger": "2.0",
  "info": {"title": "Test API", "version": "1.0.0"},
  "paths": {
    "/user": {
      "get": {
        "responses": {
          "200": {"description": "OK"}
        }
      }
    },
    "/user/{id}": {
      "parameters": [{
        "name": "id",
        "in": "path",
        "required": true,
        "type": "string"
      }],
      "get": {
        "responses": {
          "200": {"description": "OK"}
        }
      }
    }
  }
};

const config = {
  assertionFormat: 'should',
  testModule: 'supertest',
  pathName: ['/user', '/user/{id}'],
  pathParams: {
    "id": "0123"
  },
  // Example of a load test configuration for a specific path/operation
  loadTest: [{
    pathName: '/user',
    operation: 'get',
    load: {requests: 100, concurrent: 10}
  }]
};

// Generates an array of objects containing the test file content and name
const tests = stt(swaggerSpec, config);

// Iterate through generated tests and print them (or write to files)
tests.forEach(testFile => {
  console.log(`--- Test File: ${testFile.name} ---\n`);
  console.log(testFile.test);
  // Example: Writing to a file
  // fs.writeFileSync(`${testFile.name}`, testFile.test);
});

view raw JSON →