我在测试Angular组件时遇到麻烦,该组件利用[(ngModel)]
内复选框输入的两种方式ngFor
绑定。它在实际应用中正常工作。这只是测试的问题。
这是一个失败的示例测试:
import { async, ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing';
import { Component, EventEmitter, Output } from '@angular/core';
import { FormsModule } from '@angular/forms';
describe('Example Test', () => {
@Component({
template: `
<input *ngFor="let value of values"
type="checkbox"
class="checkbox-1"
[(ngModel)]="value.isSelected"
(change)="output.emit(values)">
`,
styles: [``]
})
class TestHostComponent {
@Output() output: EventEmitter<any> = new EventEmitter();
values = [
{ isSelected: true },
{ isSelected: true },
{ isSelected: true },
];
}
let testHost: TestHostComponent;
let fixture: ComponentFixture<TestHostComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [FormsModule],
declarations: [TestHostComponent],
providers: []
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(TestHostComponent);
testHost = fixture.componentInstance;
fixture.detectChanges();
});
it('should change isSelected', fakeAsync(() => {
const spy = spyOn(testHost.output, 'emit');
fixture.nativeElement.querySelectorAll('.checkbox-1')[0].click();
fixture.detectChanges();
tick();
expect(spy).toHaveBeenCalledWith([
{ isSelected: false }, // it fails because this is still true
{ isSelected: true },
{ isSelected: true },
]);
}));
});
将[(ngModel)]
与不在循环中的单个输入一起使用在类似的测试中效果很好。我什至已经记录了(ngModelChange)
发出的值,当单击复选框时,$event
应该是true
时是false
。
有什么想法吗?
答案 0 :(得分:2)
似乎执行点击的方法不会触发更改检测。相反,在复选框上调度更改事件会产生预期的结果:
it('should change isSelected', fakeAsync(() => {
const spy = spyOn(testHost.output, 'emit');
const checkbox = fixture.nativeElement.querySelectorAll('.checkbox-1')[0];
checkbox.dispatchEvent(new Event('change'));
fixture.detectChanges();
tick();
expect(spy).toHaveBeenCalledWith([
{ isSelected: false }, // This is now false
{ isSelected: true },
{ isSelected: true },
]);
}));
受this post启发的解决方案。
更新:
似乎需要等待某些控件在CheckboxControlValueAccessor上初始化或注册。如果您在创建组件后将第二个beforeEach()
修改为等待一个周期,则原始测试代码有效:
beforeEach(fakeAsync(() => {
fixture = TestBed.createComponent(TestHostComponent);
testHost = fixture.componentInstance;
fixture.detectChanges();
tick();
}));
有关完整的答案/说明,请参见this Github issue。