Mocking material design elements for unit tests
December 10, 2020 · 2 min readLucian CiobanuMaterial design offers a quick way to add some if not all of the most used components inside a web application but if you're projects requests a threshold for test coverage with unit testing, these elements can give you a hard time to test. This is the method I've been using to "introduce" these material design components to the testing suit:
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { Component, Input } from '@angular/core';
@Component({
selector: 'mat-option',
template: '<span></span>'
})
class MockMatOption {
@Input() value: any;
@Input() disabled: boolean;
}
describe('MyComponentToTest', () => {
let component: MyComponentToTest;
let fixture: ComponentFixture<MyComponentToTest>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
MyComponentToTest,
MockMatOption,
]
})
.compileComponents();
}));
As you can see, I am using the @Component decorator to create a selector and template for the mock component and I am also including the inputs this component might have; in my case, I needed value and disabled which I was using in the component HTML template. Also, make sure to add the class to the declarations array under TestBed.configureTestingModule.
Hope this helped!
Cheers,
Lucian

Web Development & Software Delivery