Jasmine测试中 Spy.and、Spy.calls、Spy.withArgs的强大之处

最近发现,在测试中遇到的很多困难,其实Jasmine已经给我们准备好了解决方案。
摘要由CSDN通过智能技术生成


最近发现,在测试中遇到的很多困难,其实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();
    }));

    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值