@loopback/testlab

  • Version 7.0.0
  • Published
  • 109 kB
  • 13 dependencies
  • MIT license

Install

npm i @loopback/testlab
yarn add @loopback/testlab
pnpm add @loopback/testlab

Overview

A collection of test utilities we use to write LoopBack tests.

Remarks

Test utilities to help write LoopBack 4 tests:

- expect - behavior-driven development (BDD) style assertions - sinon - test spies: functions recording arguments and other information for all of their calls - stubs: functions (spies) with pre-programmed behavior - mocks: fake methods (like spies) with pre-programmed behavior (like stubs) as well as pre-programmed expectations - Helpers for creating supertest clients for LoopBack applications - HTTP request/response stubs for writing tests without a listening HTTP server - Swagger/OpenAPI spec validation

Index

Variables

variable expect

const expect: Internal;

    Functions

    function createClientForHandler

    createClientForHandler: (
    handler: (req: http.IncomingMessage, res: http.ServerResponse) => void
    ) => supertest.SuperTest<supertest.Test>;
    • Create a SuperTest client connected to an HTTP server listening on an ephemeral port and calling handler to handle incoming requests.

      Parameter handler

    function createRestAppClient

    createRestAppClient: (
    app: RestApplicationLike
    ) => supertest.SuperTest<supertest.Test>;
    • Create a SuperTest client for a running RestApplication instance. It is the responsibility of the caller to ensure that the app is running and to stop the application after all tests are done.

      Parameter app

      A running (listening) instance of a RestApplication.

    function createStubInstance

    createStubInstance: <TType extends object>(
    constructor: sinon.StubbableType<TType>
    ) => StubbedInstanceWithSinonAccessor<TType>;
    • Creates a new object with the given functions as the prototype and stubs all implemented functions.

      Note: The given constructor function is not invoked. See also the stub API.

      This is a helper method replacing sinon.createStubInstance and working around the limitations of TypeScript and Sinon, where Sinon is not able to list private/protected members in the type definition of the stub instance and therefore the stub instance cannot be assigned to places expecting TType. See also - https://github.com/Microsoft/TypeScript/issues/13543 - https://github.com/DefinitelyTyped/DefinitelyTyped/issues/14811

      Parameter constructor

      Object or class to stub.

      Returns

      A stubbed version of the constructor, with an extra property stubs providing access to stub API for individual methods.

    function createUnexpectedHttpErrorLogger

    createUnexpectedHttpErrorLogger: (expectedStatusCode?: number) => LogError;
    • Creates a Logger that logs an Error if the HTTP status code is not expected

      Parameter expectedStatusCode

      HTTP status code that is expected

    function givenHttpServerConfig

    givenHttpServerConfig: <T extends HttpOptions | HttpsOptions>(
    customConfig?: T
    ) => HostPort & T;
    • Create an HTTP-server configuration that works well in test environments. - Ask the operating system to assign a free (ephemeral) port. - Use IPv4 localhost 127.0.0.1 to avoid known IPv6 issues in Docker-based environments like Travis-CI. - Provide default TLS key & cert when protocol is set to https.

      Parameter customConfig

      Additional configuration options to apply.

    function httpGetAsync

    httpGetAsync: (
    urlString: string,
    agent?: http.Agent
    ) => Promise<IncomingMessage>;
    • Async wrapper for making HTTP GET requests

      Parameter urlString

    function httpsGetAsync

    httpsGetAsync: (
    urlString: string,
    agent?: https.Agent
    ) => Promise<IncomingMessage>;
    • Async wrapper for making HTTPS GET requests

      Parameter urlString

    function inject

    inject: (
    dispatchFunc: ShotListener,
    options: ShotRequestOptions
    ) => Promise<ResponseObject>;

      function skipIf

      skipIf: <ARGS extends unknown[], RETVAL>(
      skip: boolean,
      verb: TestDefinition<ARGS, RETVAL> & { skip: TestDefinition<ARGS, RETVAL> },
      name: string,
      ...args: ARGS
      ) => RETVAL;
      • Helper function for skipping tests when a certain condition is met.

        Parameter skip

        Should the test case/suite be skipped?

        Parameter verb

        The function to invoke to define the test case or the test suite, e.g. it or describe.

        Parameter name

        The test name (the first argument of verb function).

        Parameter args

        Additional arguments (framework specific), typically a function implementing the test.

        Example 1

        skipIf(
        !features.freeFormProperties,
        describe,
        'free-form properties (strict: false)',
        () => {
        // the tests
        }
        );

      function skipOnTravis

      skipOnTravis: <ARGS extends unknown[], RETVAL>(
      verb: TestDefinition<ARGS, RETVAL> & { skip: TestDefinition<ARGS, RETVAL> },
      name: string,
      ...args: ARGS
      ) => RETVAL;
      • Helper function for skipping tests on Travis CI.

        Parameter verb

        The function to invoke to define the test case or the test suite, e.g. it or describe.

        Parameter name

        The test name (the first argument of verb function).

        Parameter args

        Additional arguments (framework specific), typically a function implementing the test.

        Example 1

        skipOnTravis(it, 'does something when some condition', async () => {
        // the test
        });

      function stubExpressContext

      stubExpressContext: (requestOptions?: ShotRequestOptions) => ExpressContextStub;

        function stubHandlerContext

        stubHandlerContext: (requestOptions?: ShotRequestOptions) => HandlerContextStub;

          function stubServerRequest

          stubServerRequest: (options: ShotRequestOptions) => IncomingMessage;

            function stubServerResponse

            stubServerResponse: (
            request: IncomingMessage,
            onEnd: ShotCallback
            ) => ServerResponse;

              function toJSON

              toJSON: {
              (value: Date): string;
              (value: Function): undefined;
              (value: unknown[]): unknown[];
              (value: object): object;
              (value: undefined): undefined;
              (value: null): null;
              (value: number): number;
              (value: boolean): boolean;
              (value: string): string;
              (value: unknown[]): unknown[];
              (value: unknown[]): unknown[];
              (value: unknown[]): unknown[];
              (value: object): object;
              (value: object): object;
              (value: object): object;
              };
              • JSON encoding does not preserve properties that are undefined As a result, deepEqual checks fail because the expected model value contains these undefined property values, while the actual result returned by REST API does not. Use this function to convert a model instance into a data object as returned by REST API

              function validateApiSpec

              validateApiSpec: (spec: any) => Promise<void>;

                Classes

                class TestSandbox

                class TestSandbox {}
                • TestSandbox class provides a convenient way to get a reference to a sandbox folder in which you can perform operations for testing purposes.

                constructor

                constructor(rootPath: string, options?: TestSandboxOptions);
                • Will create a directory if it doesn't already exist. If it exists, you still get an instance of the TestSandbox.

                  Parameter rootPath

                  Root path of the TestSandbox. If relative it will be resolved against the current directory.

                  Parameter options

                  Options to control if/how the sandbox creates a subdirectory for the sandbox. If not provided, the sandbox will automatically creates a unique temporary subdirectory. This allows sandboxes with the same root path can be used in parallel during testing.

                  Example 1

                  // Create a sandbox as a unique temporary subdirectory under the rootPath
                  const sandbox = new TestSandbox(rootPath);
                  const sandbox = new TestSandbox(rootPath, {subdir: true});
                  // Create a sandbox in the root path directly
                  // This is same as the old behavior
                  const sandbox = new TestSandbox(rootPath, {subdir: false});
                  // Create a sandbox in the `test1` subdirectory of the root path
                  const sandbox = new TestSandbox(rootPath, {subdir: 'test1'});

                property path

                readonly path: string;

                  method copyFile

                  copyFile: (
                  src: string,
                  dest?: string,
                  transform?: (content: string) => string
                  ) => Promise<void>;
                  • Copies a file from src to the TestSandbox. If copying a .js file which has an accompanying .js.map file in the src file location, the dest file will have its sourceMappingURL updated to point to the original file as an absolute path so you don't need to copy the map file.

                    Parameter src

                    Absolute path of file to be copied to the TestSandbox

                    Parameter dest

                    Optional. Destination filename of the copy operation (relative to TestSandbox). Original filename used if not specified.

                    Parameter transform

                    Optional. A function to transform the file content.

                  method delete

                  delete: () => Promise<void>;
                  • Deletes the TestSandbox.

                  method mkdir

                  mkdir: (dir: string) => Promise<void>;
                  • Makes a directory in the TestSandbox

                    Parameter dir

                    Name of directory to create (relative to TestSandbox path)

                  method reset

                  reset: () => Promise<void>;
                  • Resets the TestSandbox. (Remove all files in it).

                  method writeJsonFile

                  writeJsonFile: (dest: string, data: unknown) => Promise<void>;
                  • Creates a new file and writes the given data serialized as JSON.

                    Parameter dest

                    Destination filename, optionally including a relative path.

                    Parameter data

                    The data to write.

                  method writeTextFile

                  writeTextFile: (dest: string, data: string) => Promise<void>;
                  • Creates a new file and writes the given data as a UTF-8-encoded text.

                    Parameter dest

                    Destination filename, optionally including a relative path.

                    Parameter data

                    The text to write.

                  Interfaces

                  interface ExpressContextStub

                  interface ExpressContextStub extends HandlerContextStub {}

                    property app

                    app: express.Application;

                      property request

                      request: express.Request;

                        property response

                        response: express.Response;

                          property result

                          result: Promise<ObservedResponse>;

                            interface HandlerContextStub

                            interface HandlerContextStub {}

                              property request

                              request: IncomingMessage;

                                property response

                                response: ServerResponse;

                                  property result

                                  result: Promise<ObservedResponse>;

                                    interface HostPort

                                    interface HostPort {}
                                    • An object that requires host and port properties

                                    property host

                                    host: string;

                                      property port

                                      port: number;

                                        interface HttpOptions

                                        interface HttpOptions extends ListenOptions {}

                                          property protocol

                                          protocol?: 'http';

                                            interface HttpsOptions

                                            interface HttpsOptions extends ListenOptions, HttpsServerOptions {}

                                              property protocol

                                              protocol: 'https';

                                                interface RestApplicationLike

                                                interface RestApplicationLike {}

                                                  property restServer

                                                  restServer: RestServerLike;

                                                    interface RestServerLike

                                                    interface RestServerLike {}

                                                      property rootUrl

                                                      rootUrl?: string;

                                                        property url

                                                        url?: string;

                                                          interface TestSandboxOptions

                                                          interface TestSandboxOptions {}
                                                          • Options for a test sandbox

                                                          property subdir

                                                          subdir: boolean | string;
                                                          • The subdir controls if/how the sandbox creates a subdirectory under the root path. It has one of the following values:

                                                            - true: Creates a unique subdirectory. This will be the default behavior. - false: Uses the root path as the target directory without creating a subdirectory. - a string such as sub-dir-1: creates a subdirectory with the given value.

                                                          Type Aliases

                                                          type Client

                                                          type Client = supertest.SuperTest<supertest.Test>;

                                                            type ObservedResponse

                                                            type ObservedResponse = ResponseObject;

                                                              type ShotCallback

                                                              type ShotCallback = (response: ResponseObject) => void;

                                                                type ShotResponseCtor

                                                                type ShotResponseCtor = new (
                                                                request: IncomingMessage,
                                                                onEnd: ShotCallback
                                                                ) => ServerResponse;

                                                                  type StubbedInstanceWithSinonAccessor

                                                                  type StubbedInstanceWithSinonAccessor<T> = T & {
                                                                  stubs: sinon.SinonStubbedInstance<T>;
                                                                  };

                                                                    type TestDefinition

                                                                    type TestDefinition<ARGS extends unknown[], RETVAL> = (
                                                                    name: string,
                                                                    ...args: ARGS
                                                                    ) => RETVAL;
                                                                    • A function defining a new test case or a test suite, e.g. it or describe.

                                                                    Namespaces

                                                                    namespace should

                                                                    module 'should' {}

                                                                      variable should

                                                                      var should: Internal;

                                                                        Package Files (13)

                                                                        Dependencies (13)

                                                                        Dev Dependencies (3)

                                                                        Peer Dependencies (0)

                                                                        No peer dependencies.

                                                                        Badge

                                                                        To add a badge like this onejsDocs.io badgeto your package's README, use the codes available below.

                                                                        You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/@loopback/testlab.

                                                                        • Markdown
                                                                          [![jsDocs.io](https://img.shields.io/badge/jsDocs.io-reference-blue)](https://www.jsdocs.io/package/@loopback/testlab)
                                                                        • HTML
                                                                          <a href="https://www.jsdocs.io/package/@loopback/testlab"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>