efarley
efarley

Reputation: 8681

Angular 2 CLI how to easily include RouterTestingModule in all specs

I am working on a new project and will be using the CLI to generate the app and all files, however I've run into something that seems to stink to me and I'm hoping there is a better way to do this.

My app has routes and so in my tests I need to import the RouterTestingModule to provide mocks for the router. However since every spec we create is going to need this it would be really nice if it were included by default when a new component is created. I looked into support for custom blueprints but there isn't any support for that yet, which is a bummer since this would be super simple if I could just add that module into the blueprint.

What other options are there to include it in all specs by default without requiring every dev to remember to add it when they create a new component?

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

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ LoginComponent ],
      imports: [
        RouterTestingModule, // I don't want to have to manually add this in every spec file.
        SharedModule
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(LoginComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

Upvotes: 0

Views: 340

Answers (1)

Julia Passynkova
Julia Passynkova

Reputation: 17899

It sounds strange that routing is required for each component. Routing should be injected only to smart first, second levels components and the rest components should be dump.

Anyway if you really need it, you ca create a function that accepts TestModuleMetadata object and inject inside the required import like that

createTestModule(moduleDef: TestModuleMetadata) {
  let imports = [...(moduleDef.imports||[]), RouterTestingModule];
  return Object.assign({}, moduleDef, {imports});
}

Upvotes: 0

Related Questions