gpt4 book ai didi

angular - 使用 [(ngModel)] 不会对 ngFor 内的输入应用单元测试更改

转载 作者:太空狗 更新时间:2023-10-29 18:22:23 24 4
gpt4 key购买 nike

我在测试 Angular 组件时遇到问题,该组件使用两种方式 [(ngModel)] 绑定(bind) 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) 发出的值,当复选框被点击时 $eventtrue 而实际上它应该是

有什么想法吗?

最佳答案

似乎执行点击的方法不会触发更改检测。在复选框上调度更改事件反而给出了预期的结果:

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以获得完整的答案/解释。

关于angular - 使用 [(ngModel)] 不会对 ngFor 内的输入应用单元测试更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53661146/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com