5

I've simply added a shared module with a SharedComponent in it and used that component in the main app component:

<acs-shared></acs-shared>

All that component does is display 'Hello, world!' using a property on the component:

<h1>Hello, {{name}}!</h1>

This all works fine when running the project with npm start, but now running npm test fails, so does $(npm bin)/karma start ./karma.conf.js. The first failure is that it can't create the component because it doesn't recognize the 'acs-shared' element. Is there something special that needs to be done to test components that use other components or modules?

Chrome 54.0.2840 (Windows 10 0.0.0) App: AngularCliStarter should create the app FAILED
    'acs-shared' is not a known element:

The project is available on github: https://github.com/JasonGoemaat/angular-cli-starter

0

1 Answer 1

11

You need to import the SharedModule into the TestBed configuration. What you're doing with the TestBed is like configuring an @NgModule from scratch for the test environment

TestBed.configureTestingModule({
  imports: [ SharedModule ],
  declarations: [
    AppComponent
  ],
  providers: []
});
Sign up to request clarification or add additional context in comments.

5 Comments

Awesome, makes total sense! I imported the 'AppModule' and it worked. Is there any reason to not include the module the component is actually in? Seems like that is a better test since I could forget to import the SharedModule in my AppModule and it seems the tests would succeed but the app wouldn't work. You can also skip the declarations then.
Personally, and this is just preference, I try to keep the tests all controlled and limited from unnecessary variables. As far as the AppModule, I never import that into test test. The AppModule has too much going on. This is where you import a bunch of providers, the BroswerModule, RoutingModules and a bunch of other stuff you don't need. Even in the case of the shared module, if it has too much going on, I might just declare the component in the test bed, instead of importing the shared module. Again this is just my preference. Everyone will have their own
The more you test though, I think you'll start to figure out your own style and preferences.
Thanks for the input, I guess what I'm talking about might be more appropriate for end to end testing, or should be tests on the modules themselves that they import and export the correct things.
@PaulSamsotha Give this man a Bells!!! I'm new to Angular and I couldn't figure this out. Countless articles read and still no closer. Then I came across this hidden gem and had the light bulb moment. Thanks so much Paul!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.