要解决“Angular单元测试 - 点击按钮后更改未被检测到”的问题,可以使用fixture.detectChanges()
方法来手动触发变更检测。
以下是一个示例代码:
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { MyComponent } from './my.component';
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ MyComponent ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should update value after button click', () => {
const button = fixture.nativeElement.querySelector('button');
button.click();
fixture.detectChanges(); // 手动触发变更检测
expect(component.value).toEqual('New Value');
});
});
在上面的示例中,我们使用fixture.detectChanges()
方法来手动触发变更检测,以确保在点击按钮后更新的值能够被检测到。
请注意,fixture.detectChanges()
方法应该在对组件进行任何更改之后调用,以确保这些更改被检测到。