You have to break your angular applications to different modules. It is not recommended to create entire applications of many components with only one module.
That being said, you can import the module containing the maincomponent while configuring the TestBed. In main.component.spec.ts, you would have imported other components like this
Before
beforeEach(async(() => {
TestBed.configureTestingModule({
imports:[RouterModule.forRoot(routes)
....
....],
declarations: [NavbarComponent,
FooterComponent
....
....]
})
.compileComponents();
}));
Instead, you can directly import the AppModule.
After
import AppModule from '../app.module'
beforeEach(async(() => {
TestBed.configureTestingModule({
imports:[AppModule]
})
.compileComponents();
}));
Here AppModule contains the component NavbarComponent, FooterComponent.
EDIT
Do it with caution. Doing this is kind of short cut to solve the original problem. Because you are using real services, and not mocking them. So if you are using service which calls the server, then your test will also call the server. If your service deals with local storage, then your test will also manipulate the local storage.
Better way to do this is combination of CUSTOM_ELEMENTS_SCHEMA and stubbing of services.
CUSTOM_ELEMENTS_SCHEMA will ignore
- any non-Angular elements with a - in their name,
- any properties on elements with a - in their name which is the common rule for custom elements.
So it will not throw error if you are using some <md-icon> or <app-footer>.
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent
],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
}).compileComponents();
}));
By stubbing your router, you will avoid hitting your server, which is the recommended way. Please read more about stubbing services at offical angular guide
Injecting the real UserService could be a nightmare. The real service might ask the user for login credentials and attempt to reach an authentication server. These behaviors can be hard to intercept. It is far easier and safer to create and register a test double in place of the real UserService.