I am writing a jest unit tests for a simple angular component which have @Input property.
Here is my component
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-title',
template: '<h2 id="title" class="title">{{title}}</h2>',
styleUrls: ['./title.component.scss'],
})
export class TitleComponent implements OnInit {
@Input() title;
constructor() { }
ngOnInit() {
}
}
My unit test file
describe('TitleComponent', () => {
let component: TitleComponent;
let fixture: ComponentFixture<TitleComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
],
declarations: [TitleComponent]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TitleComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should show TEST INPUT', () => {
component.title = 'test title';
fixture.detectChanges();
const input = fixture.nativeElement.querySelector('h2').innerText;
console.log(input);
expect(input).toEqual('test title');
});
});
The console.log(input) is always undefined and my test case is failing. What I doing wrong here?🤔
It should be innerHTML
or textContent
instead of innerText
. Then it works.
fixture.nativeElement.querySelector('h2').innerHTML;
The reason is that jest uses JSDom and in JSDom the innerText property is not implemented yet. innerText implementation #1245