文章目录
最近发现,在测试中遇到的很多困难,其实Jasmine已经给我们准备好了解决方案。
Spy.and
你可以通过 and 来定义spy被调用的之后要执行什么操作。
官网介绍 https://jasmine.github.io/api/edge/Spy_and.html
Spy.and 提供的方法有以下这些:
方法 | 描述 |
---|---|
stub() | 告诉spy在被调用时什么都不做。 这是默认设置。 |
callFake(fn) | 告诉spy在被调用时,调用伪实现。要调用的fn通过参数传递。 |
callThrough() | 告诉spy在被调用时,调用真正的实现。 |
exec() | 执行当前的spy策略。 |
identity() | 返回spy的识别信息,返回类型是string。 |
returnValue(value) | 告诉spy在被调用时的返回值。 |
returnValues(…values) | 每次调用 spy 时,告诉 spy 按顺序返回指定值之一。 |
throwError(something) | 告诉spy在被调用时抛出错误。 |
// The example comes from an open source component library called ngx-tethys 【Focus point: callFake(fn)】
it('should close a dialog and get back a result before it is closed', fakeAsync(() => {
const dialogRef = dialog.open(DialogSimpleContentComponent, {
viewContainerRef: testViewContainerRef
});
flush();
viewContainerFixture.detectChanges();
// beforeClose should emit before dialog container is destroyed
const beforeCloseHandler = jasmine.createSpy('beforeClose callback').and.callFake(() => {
// dialog弹窗关闭之前,dialog元素应该存在
expect(getDialogContainerElement()).not.toBeNull('dialog container exists when beforeClose is called');
});
// 订阅事件流,并定义dialog关闭之前要调用的回调beforeCloseHandler
dialogRef.beforeClosed().subscribe(beforeCloseHandler);
// 调用dialog关闭的方法。会触发beforeClosed事件流,从而使得beforeCloseHandler被调用
dialogRef.close('Bulbasaur');
viewContainerFixture.detectChanges();
flush();
expect(beforeCloseHandler).toHaveBeenCalledWith('Bulbasaur');
// dialog弹窗关闭之前,dialog元素销毁,dialog元素不存在
expect(getDialogContainerElement()).toBeNull();
}));