当我在jasmine单元测试中更改mat复选框的模型时,它不会更新checked状态



我为材料复选框写了一个单元测试。我使用[(ngModule(]将复选框绑定到模型。第一个测试用例是可以的,点击复选框将更新模型,但是当我在下一个单元测试中更改模型时,它不会发生。换句话说,当我将enabled设置为true时,checked状态不会更改为true!如何通过最后一次单元测试?代码已上传到github

@Component({
selector: 'app-checkbox',
templateUrl: './checkbox.component.html'
})
export class CheckboxComponent implements OnInit {
enabled = false;
constructor() { }
ngOnInit(): void {
}
}

describe('CheckboxComponent', () => {
let component: CheckboxComponent;
let fixture: ComponentFixture<CheckboxComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ CheckboxComponent ],
imports: [
MatCheckboxModule,
BrowserAnimationsModule,
BrowserModule,
FormsModule
]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(CheckboxComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('click checkbox changes enabled', () => {
const checkBox = fixture.debugElement.query(By.css('input')).nativeElement as HTMLInputElement;
expect(component.enabled).toBeFalse();
checkBox.click();
expect(component.enabled).toBeTruthy();
});
it('changing enabled will alter checkbox state', (done) => {
const checkBox = fixture.debugElement.query(By.css('input')).nativeElement as HTMLInputElement;
component.enabled = true;
fixture.detectChanges();
fixture.whenStable().then(() => {
expect(checkBox.checked).toBeTrue();
done();
});
});
});
<mat-checkbox [(ngModel)]="enabled">Check me!</mat-checkbox>

您很可能需要一个对DOM/HTML的新引用。CCD_ 1是指CCD_ 2之前的旧DOM。

试试这个:

it('changing enabled will alter checkbox state', (done) => {
const checkBox = fixture.debugElement.query(By.css('input')).nativeElement as HTMLInputElement;
component.enabled = true;
fixture.detectChanges();
fixture.whenStable().then(() => {
const newCheckbox = fixture.debugElement.query(By.css('input')).nativeElement as HTMLInputElement; // grab new reference
expect(newCheckbox.checked).toBeTrue();
done();
});
});

我通过在whenSable((中添加另一个detectChanges((来解决这个问题

it('changing enabled will alter checkbox state', (done) => {
const checkBox = fixture.debugElement.query(By.css('input')).nativeElement as HTMLInputElement;
component.enabled = true;
fixture.detectChanges();
fixture.whenStable().then(() => {
fixture.detectChanges(); // <--- this line
expect(checkBox.checked).toBeTrue();
done();
});
});

最新更新