【问题标题】:How to mock the toastr in Angular?如何在 Angular 中模拟烤面包机?
【发布时间】:2019-09-16 05:43:07
【问题描述】:

我不确定我是否写了一个关于这个问题的好标题。 如何模拟和绕过这2条红线?

fit('Should call the sub entity list', () => {

    expect(component.subentity.length).toBe(0);

    spyOn(subentitysvc, 'getSubEntityList').and.returnValue(of(modelMock));
    component.getSubEntityList(1);
    fixture.detectChanges();
    expect(subentitysvc.getSubEntityList).toHaveBeenCalled();

    spyOn(toastr, 'error').and.callFake(() => { });

})

【问题讨论】:

    标签: angular unit-testing rxjs


    【解决方案1】:

    只要你使用jasmine,就可以窥探toastr.error方法:

    spyOn(toastr, 'error').and.callThrough();
    

    除了callThrough,您还可以使用returnValuecallFake

    【讨论】:

    • 其实我试过call fake,但问题是callfake之后我不知道如何进行下一步:(
    • 这个模拟的预期行为是什么。虽然我知道error 方法返回void
    • 什么问题?你有错误吗?请尝试将最后一个间谍移到component.getSubEntityList(1);上方
    • 它给了我这个错误信息。错误: : 找不到要监视的对象 for error() 用法:spyOn(, )
    • 你在组件中有this.toastr,所以在测试中它应该是component.toastr,不是吗?
    【解决方案2】:

    我预计您在测试中没有正确设置 toastr 服务,因此请查看以下更改。您需要在创建组件之前进行监视,它才能正常工作。

    我已将这一行 spyOn(TestBed.get(ToastrService), 'error'); 向上移动,并假设您的烤面包机服务名为 ToastrService

    fit('Should call the sub entity list', () => {
    
        expect(component.subentity.length).toBe(0);
    
        spyOn(subentitysvc, 'getSubEntityList').and.returnValue(of(modelMock));
        spyOn(TestBed.get(ToastrService), 'error');
        component.getSubEntityList(1);
        fixture.detectChanges();
        expect(subentitysvc.getSubEntityList).toHaveBeenCalled();
    
    })
    

    希望这会有所帮助。 附:我建议每次测试只使用一个断言,因为这样更容易诊断问题。所以你的第一行应该是component.subentity = []

    【讨论】:

      猜你喜欢
      • 2019-08-05
      • 2018-05-24
      • 2018-05-12
      • 2019-03-29
      • 1970-01-01
      • 2018-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多