出于某种原因,我无法在测试中为我的 mat-checkbox 设置 checked 道具。不知道这里可能是什么问题
html
<form class="example-form">
<mat-checkbox [checked]="localValue" [disabled]="disabled" (click)="sendCheck()"></mat-checkbox>
</form>
ts
localValue!: boolean
ngOnInit(): void {
this.localValue = this.value ? this.value === 'true' : false
}
sendCheck() {
this.localValue = !this.localValue
this.cellValueChanged.emit(this.localValue)
}
spec.ts
function createComponent<T>(componentType: Type<T>, extraDeclarations: any[] = []) {
TestBed.configureTestingModule({
imports: [MatCheckboxModule, FormsModule, ReactiveFormsModule],
declarations: [componentType, ...extraDeclarations],
}).compileComponents();
return TestBed.createComponent<T>(componentType);
}
let loader: HarnessLoader
let checkBoxHarness: MatCheckboxHarness
let checkboxDebugElement: DebugElement
let checkboxNativeElement: HTMLElement
let checkboxInstance: MatCheckbox
let inputElement: HTMLInputElement
TestBed.resetTestEnvironment()
TestBed.initTestEnvironment(BrowserDynamicTestingModule, platformBrowserDynamicTesting())
let component: BooleanComponent
let fixture: ComponentFixture<BooleanComponent>
beforeEach(async () => {
fixture = createComponent(BooleanComponent, [CellComponent])
component = fixture.debugElement.componentInstance
loader = TestbedHarnessEnvironment.loader(fixture)
checkBoxHarness = await loader.getHarness(MatCheckboxHarness)
checkboxDebugElement = fixture.debugElement.query(By.directive(MatCheckbox))!
checkboxNativeElement = checkboxDebugElement.nativeElement
checkboxInstance = checkboxDebugElement.componentInstance
inputElement = <HTMLInputElement>checkboxNativeElement.querySelector('input')
})
it('check', fakeAsync(() => {
component.field = {
guid: '',
field_type_code: '',
operationCode: { multiple: true },
}
expect(checkboxInstance.checked).toBe(false)
expect(inputElement.checked).toBe(false)
component.localValue = true
fixture.detectChanges()
console.log(component.localValue)
console.log(checkboxInstance.checked)
console.log(inputElement.checked)
expect(checkboxInstance.checked).toBe(true)
inputElement.click()
fixture.detectChanges()
flush()
console.log(checkboxInstance.checked)
expect(checkboxInstance.checked).toBe(false)
}))
我尝试过基本上设置属性,该属性必须检查为真,但它没有改变任何东西。还尝试将 FormControl 和 ngModel 与 standalone 一起使用,但情况更糟。