Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Dependency management for Angular unit tests using TestModuleMetadata

some.component.spec.ts:

import { TestModuleMetadata } from '@angular/core/testing';
import { createOtherTestModuleMetadata } from 'other.component.spec';
import { compileTestModuleMetadata } from 'app.module';

...

export function createSomeComponentTestModuleMetadata(): TestModuleMetadata {
  const testModuleMetadata: TestModuleMetadata = {
    declarations: [
      ...
    ],
    imports: [
      ...
    ],
    providers: [
      ...
    ]
  };

  const transitiveTestModuleMetadataDefinitions: TestModuleMetadata[] = [
    createOtherTestModuleMetadata()
  ];

  return compileTestModuleMetadata(transitiveTestModuleMetadataDefinitions, testModuleMetadata);
}

describe('SomeComponent', () => {
  let component: SomeComponent;
  let fixture: ComponentFixture<SomeComponent>;

  beforeEach(async(() => {
    TestBed
      .configureTestingModule(createSomeComponentTestModuleMetadata())
      .compileComponents();
  }));

  ...
});

other.component.spec.ts:

import { TestModuleMetadata } from '@angular/core/testing';
import { compileTestModuleMetadata } from 'app.module';

...

export function createOtherTestModuleMetadata(): TestModuleMetadata {
  const testModuleMetadata: TestModuleMetadata = {
    declarations: [
      ...
    ],
    imports: [
      ...
    ],
    providers: [
      ...
    ]
  };

  const transitiveTestModuleMetadataDefinitions: TestModuleMetadata[] = [
  ];

  return compileTestModuleMetadata(transitiveTestModuleMetadataDefinitions, testModuleMetadata);
}

app.module.ts

import { TestModuleMetadata } from '@angular/core/testing';

...

export function compileTestModuleMetadata(
  transitiveTestModuleMetadataDefinitions: TestModuleMetadata[],
  testModuleMetadata: TestModuleMetadata
) {
  const artefactTypes = [
    'providers',
    'declarations',
    'imports'
  ];

  for (const transitiveTestModuleMetadata of transitiveTestModuleMetadataDefinitions) {
    for (const artefactType of artefactTypes) {
      if (transitiveTestModuleMetadata[artefactType]) {
        for (const artefact of transitiveTestModuleMetadata[artefactType]) {
          if (!testModuleMetadata[artefactType].includes(artefact)) {
            testModuleMetadata[artefactType].push(artefact);
          }
        }
      }
    }
  }

  return testModuleMetadata;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.