0

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();
  });
});
efarley
  • 8,371
  • 12
  • 42
  • 65
  • Create on module for all your reusable imports and include it here. – Babar Hussain Apr 20 '17 at 22:04
  • I did that, I include the actual import for `RouterModule` inside the `SharedModule` that you'll see I'm importing in the spec. The issue is that in the test I need to import `RouterTestingModule` instead of `RouterModule` for the tests to run. – efarley Apr 20 '17 at 22:20
  • Well it doesn't seem to hurt anything to include `RouterTestingModule` into the app instead of only including it in the specs. – efarley Apr 20 '17 at 22:27

1 Answers1

0

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});
}
Julia Passynkova
  • 17,256
  • 6
  • 33
  • 32
  • I don't include the routing in each component. I include it in a `SharedModule` which then imported into every component. The issue is that that import is `RouterModule` while in the spec it changes to `RouterTestingModule` so the specs need that additional import. I've found I can just import the testing module into the same shared module and it doesn't seem to hurt anything. – efarley Apr 20 '17 at 23:39