Skip to main content

TestContainer

An isolated Container for tests.

The Container is a process-wide singleton, which makes it awkward to mock. TestContainer solves that: create one in beforeEach() and it takes over the Container for that test, letting you replace any factory with a stub. reset() in afterEach() puts it back.

Info

A test framework like Jest runs test files in parallel across cores, and the it() blocks within a file serially. So a TestContainer never leaks into a test running in parallel.

@example
beforeEach(async () => {
container = await TestContainer.create({ mocks: [] }, { factoryTimeoutInMs: 500 });
});

afterEach(async () => {
await TestContainer.reset();
});
@group

Functions/Container

Index

Constructors

Methods

Constructors

constructor

Methods

staticcreate

  • create(subjects: TestContainerSubjects, options?: TestContainerOptions): Promise<Container>
  • To take over the Container for one test, replacing the factories you name.

    @example
    await TestContainer.create({
    mocks: [
    { type: MyClass, value: jest.fn() },
    { metadata: { key: 'value' }, type: AnotherClass, value: new AnotherClass() },
    ],
    }, { factoryTimeoutInMs: 500 });

    Parameters

    • subjects: TestContainerSubjects

      The subjects being mocked.

      • mocks is an array of objects, to override the default factories.
        • Use metadata?: { [key: string]: string } to identify the factory being mocked.
        • Use type: Constructable<T> | string to identify the class being mocked.
        • Use value: T to provide the mocked value.
    • optionaloptions: TestContainerOptions

      Options to configure TestContainer.

      • factoryTimeoutInMs?: number is to override the default container timeout.
      • force?: boolean performs a complete container reset.

    Returns Promise<Container>

staticreset

  • reset(): Promise<void>
  • To destroy every factory in the Container. Because it destroys the whole Container and not only the mocks, it must always be called in your teardown block - otherwise the next test starts against a Container this test left behind.


    Returns Promise<void>

Page Options