【问题标题】:Cannot get spyOn test to work properly- Angular无法让 spyOn 测试正常工作 - Angular
【发布时间】:2018-09-03 14:45:26
【问题描述】:

由于某种原因,我无法让我的测试正常工作,并且一直抛出错误:

isCurrentStatus 上的预期间谍等于 true。

被调用的函数只是评估传入的变量是否等于当前持有的status 属性,并返回真或假。没什么大不了的...

测试

it('should return true if current status = status passed in', () => {
    const statusSpy = spyOn(component, 'isCurrentStatus');
    component.event = failedEvent;
    component.isCurrentStatus('failed');
    expect(statusSpy).toEqual(true);
  })

组件

event: MyEvent;

isCurrentStatus(status: string): boolean {
    return this.event.status === status;
  }

更新

我刚刚将spyOn 移动到beforeEach() 部分,现在返回:

预计undefined 等于true

【问题讨论】:

    标签: javascript angular typescript testing karma-runner


    【解决方案1】:

    您可以在函数上创建一个 spyOn 并检查它返回的不同值:

    spyOn(component, 'isCurrentStatus').and.callThrough();
    component.event = failedEvent;
    const statusResult = component.isCurrentStatus('failed');
    expect(statusResult).toBeTruthy();
    

    【讨论】:

      【解决方案2】:

      Expected spy on isCurrentStatus to equal true. 这是因为spyOn 实际上创建了一个spy。然后你尝试像expect(Spy).toEqual(Boolean); 这样的东西,所以你得到这样的错误。

      expected undefined to equal true - 因为beforeEach() 的作用域不在你的测试函数(it())作用域中

      因为你想测试返回值 - 你不需要在这里窥探。只需调用函数并检查其结果。

      当您需要测试而不是返回值而是其他东西时需要 Spy - 例如,它是注入依赖项的函数,但您需要确信它被调用了。所以,你创建了一个间谍。或者:您需要检查函数调用了多少次、传递了哪些参数等。或者何时需要模拟其行为。

      【讨论】:

        【解决方案3】:

        试试这个来测试返回值

        expect(component.isCurrentStatus('failed')).toEqual(true);
        

        您可以检查该方法是否被调用

        const statusSpy = spyOn(component, 'isCurrentStatus').and.callThrough();
        ...
        expect(statusSpy).toHaveBeenCalledTimes(1);
        

        你可以检查参数

        expect(statusSpy).toHaveBeenCalledWith('failed')
        

        【讨论】:

          猜你喜欢
          • 2017-10-12
          • 1970-01-01
          • 1970-01-01
          • 2019-07-11
          • 1970-01-01
          • 2017-01-24
          • 2011-11-14
          • 2018-09-13
          • 1970-01-01
          相关资源
          最近更新 更多