Options
All
  • Public
  • Public/Protected
  • All
Menu

@tempworkssoftware/open-api-mocker

Index

Top-Level Exports

configure

configure: (settings: Settings) => void

Provide settings to affect the behavior of the fetchMock function.

Type declaration

fetchMock

fetchMock: (requestInfo: RequestInfo, requestInit?: RequestInit) => Promise<Response>

Returns a promise which resolves to a generated mock response based on the current settings. If no matching operation could be found in any of the generatedMockApis, the returned promise will resolve to undefined. This allows the consumer to easily implement other fallback logic of their choice.

Type declaration

    • (requestInfo: RequestInfo, requestInit?: RequestInit): Promise<Response>
    • Parameters

      • requestInfo: RequestInfo
      • Optional requestInit: RequestInit

      Returns Promise<Response>

generateDescriptions

generateDescriptions: (apiOptions: ApiGenerationOptions | ApiGenerationOptions[]) => Promise<void>

A function for generating operation mock files for one or more Open API 2.0 definitions. This function expects to be called in a node environment.

At the provided outputPath, this function will generate a folder for each operation named for its operationId. Inside that folder, 2 files will be generated:

  • defaultMockResponse_DONT_EDIT.json - This file contains a default MockResponseDescription which describes how to generate a mock response for the operation. This file is generated based on the provided apiDefinition, but you can customize how it is generated by passing a getDefaultMockRules function.
  • extendMockResponse.js - This file contains a ExtendMockResponse function which will be called at runtime when processing a request for this operation. Feel free to edit this file to provide more specific randomness constraints than what was generated for this operation in the defaultMockResponse_DONT_EDIT.json file.

Type declaration

mock

mock: (operationSpecifier: OperationSpecifier, body: RegisteredMockBody, responseInit?: RegisteredMockResponseInit) => void

Programmatically set a mock for the specified operation. After this function has been called, the provided mock body will override all existing mock mock body descriptions for this operation until resetMock or resetMocks has been called. If responseInit is provided, it will be merged on top of the responseInit from existing mock descriptions until resetMock or resetMocks has been called.

Type declaration

partialMock

partialMock: (operationSpecifier: OperationSpecifier, partialBody: RegisteredMockBody, responseInit?: RegisteredMockResponseInit) => void

Programmatically set a partial mock for the specified operation. After this function has been called, the provided mock body and responseInit will be deeply merged on top of all existing mock mock body descriptions for this operation until resetMock or resetMocks has been called.

Type declaration

resetMock

resetMock: (operationSpecifier: OperationSpecifier) => void

If any mocks have been set for the specified operation by calling mock or partialMock, this function will clear them.

Type declaration

resetMocks

resetMocks: () => void

If any mocks have been set by calling mock or partialMock, this function will clear them all.

Type declaration

    • (): void
    • Returns void

Settings

GeneratedMockApi

GeneratedMockApi: { apiDefinition: object; operations: {} }

The default export of the mockIndex.js file, which is created by the generateDescriptions function.

Type declaration

  • apiDefinition: object
  • operations: {}
    • [operationId: string]: GeneratedOperationMockImports | GeneratedOperationMocks

GeneratedMockApiSettings

GeneratedMockApiSettings: { baseUrl?: string; generatedMockApi: GeneratedMockApi; useCaseSensitivePathAndParameterMatching?: boolean }

Settings for a particular mock API, which will affect the behavior of the fetchMock function.

Type declaration

  • Optional baseUrl?: string

    Any requests with URLs starting with this baseUrl will be mapped to this mock api. In addition, this baseUrl will be removed from the request URL before looking up the mock response in the OpenAPI paths.

    You should provide this if you have multiple generated mock APIs.

  • generatedMockApi: GeneratedMockApi

    When the generateDescriptions function is run, it creates mock files for each operation in the apiDefinition. The generateDescriptions function also creates a mockIndex.js file in the API's output directory, which re-exports all of the operation files. This property should be a reference to the default export of that mockIndex.js file.

  • Optional useCaseSensitivePathAndParameterMatching?: boolean

    Defaults to true if not provided. In the process of matching a request to a mock response, the URL of the request must be compared to the path strings in the OpenAPI definition. If this flag is true (or not provided), that path comparison will be case-sensitive, which is how URL matching should work. However, if you would like, you can set this to false to make the comparison case-insensitive. This will also affect how query parameters are mapped to parameter values, and how the valueOfParameter MockSchema property is interpreted.

Settings

Settings: { generatedMockApis: GeneratedMockApiSettings[]; logMockResults?: boolean; onInvalidRequestParameter?: (error: string, infoObject: object) => void }

Settings which are passed to the configure function, and which will affect the behavior of the fetchMock function.

Type declaration

  • generatedMockApis: GeneratedMockApiSettings[]

    Settings for each mock API that was generated by the generateDescriptions function.

  • Optional logMockResults?: boolean

    When true, all mock results will be logged using console.log.

  • Optional onInvalidRequestParameter?: (error: string, infoObject: object) => void

    If provided, this function will be called when attempting to construct a mock response to a request that contains a parameter that is invalid according to the OpenAPI definition.

      • (error: string, infoObject: object): void
      • Parameters

        • error: string
        • infoObject: object

        Returns void

Mock Response Description

ExtendMockResponse

ExtendMockResponse: (parameters: {}, utils: { seed: string }) => void | MockResponseDescription

This function will be called at runtime when processing a request for a given API operation. It receives the operation parameters as an argument and gives you an opportunity to provide more specific randomness constraints than what was generated for this operation in the defaultMockResponse_DONT_EDIT.json file. The return value of this function will be deeply merged with the object in the defaultMockResponse_DONT_EDIT.json file before generating the mock response.

param

The operation parameters provided to the request.

param

Utilities that might be helpful in generating a mock response.

Type declaration

    • Parameters

      • parameters: {}
        • [x: string]: any
      • utils: { seed: string }
        • seed: string

          The seed used to generate random values. This seed will be a hash of the incoming request object. It is recommended to use this seed if you plan to generate any random values inside the ExtendMockResponse function.

      Returns void | MockResponseDescription

MockResponseDescription

MockResponseDescription: Partial<ResponseInit> & MockResponseBodyDescription

This object describes how to randomly generate a particular mock API response. It is an intersection of the properties of ResponseInit and {@link MockResponseBodyDescription}.

MockSchema

MockSchema: Merge<JSONSchema4, { items?: MockSchema; properties?: {}; type?: JSONSchema4["type"] | string }> & MockSchemaSpecialRules

An object in JSON Schema format, which describes the structure and constraints for generating a portion of an API response.

For example, if your MockSchema uses the JSON Schema property enum like this:

{
  type: 'string',
  enum: ['red', 'green', 'blue']
}

Then the randomly-generated value for that schema will be either 'red', 'green', or 'blue'. This is primarily accomplished by using the excellent library json-schema-faker. You can find all supported JSON Schema properties here. In addition, @tempworkssoftware/open-api-mocker supports the special MockSchema properties documented here: {@link MockSchemaSpecialRules}

ResponseBody

ResponseBody: string | Blob | ArrayBuffer | FormData | ReadableStream | URLSearchParams

Runtime Mocking

OperationSpecifier

OperationSpecifier: string | [string, string]

Either an operationId or a baseUrl, operationId pair.

RegisteredMockBody

RegisteredMockBody: FunctionOfParams<any> | any

RegisteredMockResponseInit

RegisteredMockResponseInit: FunctionOfParams<ResponseInit> | ResponseInit

Generate Descriptions

ApiGenerationOptions

ApiGenerationOptions: { apiDefinition: object | string; customGeneratedFiles?: string[]; customGeneratedOperationFiles?: string[]; getDefaultMockRules?: (schema: JSONSchema4, schemaName: string, schemaFullName: string, operationObject: Operation) => Partial<MockSchema> | void; onGenerateApi?: (apiInfo: ParsedApiToGenerate) => void | Promise<any>; onGenerateOperation?: (operationInfo: { operation: Operation & {}; operationOutputDirectory: string; path: string }) => void | Promise<any>; outputPath: string; preserveOutputFilePaths?: string[]; useDynamicImportsInMockIndex?: boolean }

Options passed to the generateDescriptions function.

Type declaration

  • apiDefinition: object | string

    The OpenAPI 2.0 (Swagger) definition location or structure. If a string, can be a URL for requesting an OpenAPI definition JSON file, or an absolute file path to a local OpenAPI definition JSON file.

  • Optional customGeneratedFiles?: string[]

    An array of file paths relative to the outputPath for this API specifying additional files that will be generated when generateDescriptions() is run, and are therefore safe to delete without warning before new files are generated. If you use the onGenerateApi callback to generate custom files for the API, the user will be warned about deleting those files unless they're included in this array.

  • Optional customGeneratedOperationFiles?: string[]

    An array of file paths relative to an operation directory specifying additional files that will be generated when generateDescriptions() is run, and are therefore safe to delete without warning before new files are generated. If you use the onGenerateOperation callback to generate custom files within each operation directory, the user will be warned about deleting those files unless they are included in this array.

  • Optional getDefaultMockRules?: (schema: JSONSchema4, schemaName: string, schemaFullName: string, operationObject: Operation) => Partial<MockSchema> | void

    Given a partial JSON-schema for an api response, return mock schema properties to add to that schema. For example, you could check if the schemaName is 'emailAddress' and add a chance property of 'email'.

    if (schemaName === 'emailAddress') {
      return { chance: 'email' }
    }
    

    This would mean that, by default, every property named 'emailAddress' returned from this api would be mocked by the chance.js email generator.

    Note that this function is called recursively for every successful response schema in the api definition. The schemaFullName will be a concatenated key path representing the position of that schema in the response. Array items will be identified by the string '[items]'. For example, you might see a schemaFullName like this:

    'EmployeesByIdGetResponse.data[items].firstName'
    

    Although this function could be used to customize the response for individual operations, it is designed to be used for broad defaults.

      • (schema: JSONSchema4, schemaName: string, schemaFullName: string, operationObject: Operation): Partial<MockSchema> | void
      • Parameters

        • schema: JSONSchema4
        • schemaName: string
        • schemaFullName: string
        • operationObject: Operation

        Returns Partial<MockSchema> | void

  • Optional onGenerateApi?: (apiInfo: ParsedApiToGenerate) => void | Promise<any>

    This function will be called after generating files for each API. It could be used to generate custom files using the fully resolved api definition. If you do generate custom files here, you will want to pass those fileNames into the customGeneratedFiles option to mark them as safe to delete without warning the user before new files are generated.

  • Optional onGenerateOperation?: (operationInfo: { operation: Operation & {}; operationOutputDirectory: string; path: string }) => void | Promise<any>

    This function will be called after generating files for each API operation. It could be used to generate custom operation code, such as a function for actually making the request or a TypeScript response type. If you do generate custom operation files here, you will want to pass those fileNames into the customGeneratedOperationFiles option to mark them as safe to delete without warning the user before new files are generated.

      • (operationInfo: { operation: Operation & {}; operationOutputDirectory: string; path: string }): void | Promise<any>
      • Parameters

        • operationInfo: { operation: Operation & {}; operationOutputDirectory: string; path: string }
          • operation: Operation & {}
          • operationOutputDirectory: string
          • path: string

        Returns void | Promise<any>

  • outputPath: string

    The absolute path to a directory where the generated code for this apiDefinition will be created.

  • Optional preserveOutputFilePaths?: string[]

    An array of file paths relative to the outputPath that should not be deleted when generateDescriptions() is run.

  • Optional useDynamicImportsInMockIndex?: boolean

    Defaults to true. Determines if dynamic imports will be used in the generated mockIndex file, which is the file that imports each of the individual operation mock files and provides them in a default export.

ParsedApiToGenerate

ParsedApiToGenerate: Merge<ApiGenerationOptions, { apiDefinition: SwaggerApi; operationsKeyedByOperationId: {}; rawApiDefinition: {} }>

A representation of an entire apiDefinition, which will be passed as an argument into the onGenerateApi function of the ApiGenerationOptions

Generated using TypeDoc