I created a new project with Angular 2.0 RTM with Angular CLI 1.0.0-beta 16:
ng init
and then ran:
ng generate component my-new-component
and then ran:
ng test
and got this:
'app-my-new-component' is not a known element:
1. If 'app-my-new-component' is an Angular component, then verify that it is part of this module.
2. If 'app-my-new-component' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schema' of this component to suppress this message. ("
</h1>
<p>The mean of life is {{answer}}</p>
[ERROR ->]<app-my-new-component></app-my-new-component>"): AppComponent@4:0
Error: Template parse errors:
at TemplateParser.parse (http://localhost:9877/_karma_webpack_/0.bundle.js:8669:19)
at RuntimeCompiler._compileTemplate (http://localhost:9877/_karma_webpack_/0.bundle.js:17854:51)
at http://localhost:9877/_karma_webpack_/0.bundle.js:17777:83
at Set.forEach (native)
at compile (http://localhost:9877/_karma_webpack_/0.bundle.js:17777:47)
at RuntimeCompiler._compileComponents (http://localhost:9877/_karma_webpack_/0.bundle.js:17779:13)
at RuntimeCompiler._compileModuleAndAllComponents (http://localhost:9877/_karma_webpack_/0.bundle.js:17696:37)
at RuntimeCompiler.compileModuleAndAllComponentsSync (http://localhost:9877/_karma_webpack_/0.bundle.js:17684:21)
at TestingCompilerImpl.compileModuleAndAllComponentsSync (http://localhost:9877/_karma_webpack_/0.bundle.js:24662:35)
at TestBed._initIfNeeded (webpack:///home/adam/monctonug/~/@angular/core/bundles/core-testing.umd.js:1059:0 <- src/test.ts:4568:40)
I've tried reordering components, didn't help. What is the correct way to fix this problem?
Debugging the errorlinkUse the element name in the error to find the file(s) where the element is being used. Check that the name and selector are correct. Make sure that the component is correctly imported inside your NgModule or standalone component, by checking its presence in the imports field.
In Angular 9 and 10 we can notice that the “my-element is not a known element” error is missing when our tests don't have all required stubs. Make sure to check debug messages when running tests and add all absent stubs. Otherwise, you will have to update your test suite when the Angular team fixes this bug.
A mock component in Angular tests can be created by MockComponent function. The mock component respects the interface of its original component, but all its methods are dummies. To create a mock component, simply pass its class into MockComponent function.
TestBed is the primary api for writing unit tests for Angular applications and libraries.
I was facing the same issue and it turn out that for tests you need to declare used components as well:
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent,
MyNewComponent
],
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With