如何在 angular 单元测试中访问 @Input 属性
How to access @Input property in angular unit test
我正在为具有@Input 属性.
的简单 angular 组件编写一个有趣的单元测试
这是我的组件
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() {
}
}
我的单元测试文件
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');
});
});
console.log(input) 总是未定义,我的测试用例失败了。
我在这里做错了什么?
应该是innerHTML
或textContent
而不是innerText
。然后就可以了。
fixture.nativeElement.querySelector('h2').innerHTML;
原因是 jest 使用了 JSDom,而在 JSDom 中,innerText 属性 还没有实现。 innerText implementation #1245
我正在为具有@Input 属性.
的简单 angular 组件编写一个有趣的单元测试这是我的组件
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() {
}
}
我的单元测试文件
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');
});
});
console.log(input) 总是未定义,我的测试用例失败了。 我在这里做错了什么?
应该是innerHTML
或textContent
而不是innerText
。然后就可以了。
fixture.nativeElement.querySelector('h2').innerHTML;
原因是 jest 使用了 JSDom,而在 JSDom 中,innerText 属性 还没有实现。 innerText implementation #1245