Skip to content

pashak09/fixturio

Repository files navigation

fixturio

test Coverage Status npm shield

Installation

yarn add -D fixturio

Fixturio excels at resolving complex object dependencies. It automatically analyzes the dependencies between objects and determines the optimal order in which they should be loaded. This library utilizes the duck typing approach. If an exported class has an install method, it will be marked as a fixture.

Inject dependencies

To inject dependencies into the constructor, you need to define the getInjectDependencies method in the fixture class and provide a container that implements the ServiceContainerInterface interface. Note that the order of definition is important. Dependencies will be injected in the same order they are defined.

import {
  FixtureInterface,
  FixtureBucket,
  DependencyInjectable,
  InjectDependency,
} from 'fixturio';

export class ArticleFixture implements FixtureInterface<unknown>, DependencyInjectable {
  constructor(
    //1
    private readonly objectSaver: ObjectSaver,
    //2
    private readonly somethingElse: SomethingElse
  ) {
  }

  getInjectDependencies(): readonly InjectDependency[] {
            //1,             2
    return [ObjectSaver, SomethingElse];
  }

  async install(fixtureBucket: FixtureBucket): Promise<unknown> {
    //...
  }
}

//Container.ts
export class AppContainer implements ServiceContainerInterface {
    private readonly mapper: Record<string, unknown> = {};

    getService<TInput = unknown, TResult = TInput>(
        typeOrToken: InjectDependency<TInput> | string
    ): TResult {
        return <TResult>this.mapper[typeOrToken.toString()];
    }
}

//fixtureLoader.ts
(async (): Promise<void> => {
    const fixtureContainer = new FixtureContainer(new AppContainer());

    await fixtureContainer.installFixtures({
      filePatterns: ['fixtures/**/*.ts'],
      rootDir: path.cwd(),
    });
})();

Dependencies between fixtures

To define dependencies between fixture classes, you need to implement the getFixtureDependencies method.

import {
  FixtureInterface,
  FixtureBucket,
  DependentFixtureInterface,
  InjectDependency,
} from 'fixturio';

//AFixture.ts
export class AFixture implements FixtureInterface<unknown>, DependentFixtureInterface {
  getFixtureDependencies(): readonly FixtureDependency[] {
    return [BFixture];
  }

  async install(fixtureBucket: FixtureBucket): Promise<unknown> {
    //...
  }
}

//BFixture.ts
export class BFixture implements FixtureInterface<unknown> {
  async install(fixtureBucket: FixtureBucket): Promise<unknown> {
    //...
  }
}

Examples

More examples can be found in examples folder

License

MIT