Resolving CUSTOM_ELEMENTS_SCHEMA error with unit testing Angular 7 components

March 21, 2019, 9:09 pm
Author: James Griffiths

Unit testing an Angular component that makes use of custom components and experiencing the following error warning?

'mi-accordion' is not a known element:
1. If 'mi-accordion' is an Angular component, then verify that it is part of this module.
2. If 'mi-accordion' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schema' of this component

The error provides some clues as to what you might want to do to fix the issue - and normally that would be the end of the matter.

The problem here though is that you might already have added the CUSTOM_ELEMENTS_SCHEMA to the application's root module or within a component's feature module....all of which makes the above 'fixes' appear nonsensical.

Resolving this error is thankfully quite simple however:

  1. Import the CUSTOM_ELEMENTS_SCHEMA into the unit testing module
  2. Declare the CUSTOM_ELEMENTS_SCHEMA within the configureTestingModule schemas

All of which will look like the following (in an example unit test):

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { MiAccordionComponent } from './mi-accordion.component';

describe('MiAccordionComponent', () => {
  let component: MiAccordionComponent;
  let fixture: ComponentFixture< MiAccordionComponent >;
  let element;
  let debug;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ MiAccordionComponent ],
      schemas: [
        CUSTOM_ELEMENTS_SCHEMA
      ],
    })
    .compileComponents();
  }));
   

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

});

Hopefully with those additions to your unit testing module CUSTOM_ELEMENTS_SCHEMA errors should now be a thing of the past.

Categories

« Return to Posts

Post a comment

All comments are welcome and the rules are simple - be nice and do NOT engage in trolling, spamming, abusiveness or illegal behaviour. If you fail to observe these rules you will be permanently banned from being able to comment.