【发布时间】:2020-06-30 19:22:52
【问题描述】:
我正在尝试学习 Jasmine,但我不确定我是否正确地做到了这一点。当我运行这个测试用例时,在expect(component.roleModal.visible).toBeTrue(); 行我收到一条错误消息Expected false to be true。
describe('ManageRolesComponent', () => {
let component: ManageRolesComponent;
let fixture: ComponentFixture<ManageRolesComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [FormsModule],
providers: [HttpClient, HttpHandler],
declarations: [ManageRolesComponent, RoleModalComponent],
schemas: [NO_ERRORS_SCHEMA]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ManageRolesComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should open the add modal', () => {
spyOn(component, 'onOpenAdd').and.callThrough();
expect(component.roleModal.visible).toBeTrue();
expect(component.roleModal.state).toBe(ModalRoleState.Add);
});
});
函数onOpenAdd() 非常简单:
public onOpenAdd() {
this.roleModal.state = ModalRoleState.Add;
this.roleModal.open();
}
与open()相同:
public open() {
this.visible = true;
}
当测试执行失败时,这是为什么?我这样做正确吗?我将值 visible 明确设置为 true 那么为什么测试是假的?
【问题讨论】:
-
你在你的组件上使用
ngOnInit吗? -
@Roy 是的,我愿意...
-
我认为您在
spyOn和expect之间缺少组件本身的初始化:component.ngOnInit(); -
似乎在
spyOn之后我必须明确运行component.onOpenAdd();。我以为这就是.and.callThrough();所做的…… -
不,
and.callThrough()是必需的,间谍仍会跟踪对它的所有调用,但此外它将委托给实际实现。 您也可以直接返回价值。
标签: javascript angular typescript karma-jasmine