【问题标题】:Angular unit test spyOn not detecting my callAngular 单元测试 spyOn 未检测到我的呼叫
【发布时间】:2018-01-12 03:16:04
【问题描述】:

我遇到了无法解决的单元测试问题。 这是我的测试:

fit('should call the alert service in case something went wrong getting the list of files', async(() => {
     spyOn(this.component.alert, 'error');
     this.component.onInputChange('error');
     this.fixture.whenStable().then((() => {
         expect(this.component.alert.error).toHaveBeenCalledWith('an error occured');
     }));
}));

这是我正在测试的组件的一部分:

private onInputChange (search: string) {
    const that = this;
    this.translateFileService.getVideoFiles(search)
        .then(files => (files.length) ? this.files = files : '')
        .catch(this.alert.error.bind(that));
}

出于测试目的, translateFileService 被模拟如下:

class TranslateFileServiceMock {

    getVideoFiles (search: string): Promise<IcoFile[]> {
        const fileList = [
            IcoFile.fromJSON({id: '0', label: 'test0', creationTime: '2017-07-01'}),
            IcoFile.fromJSON({id: '1', label: 'test1', creationTime: '2017-07-02'}),
            IcoFile.fromJSON({id: '2', label: 'test2', creationTime: '2017-07-03'}),
        ];

        return new Promise<IcoFile[]>((resolve, reject) => {
            if (search === 'error') return reject('an error occured');
            return resolve(fileList.filter(f => f.label.includes(search)));
        });
    }

}

onInputChange 方法调用我的组件中的 alert 属性表示的警报服务。 警报服务不是模拟的,它是真正的服务。实际上调用了它的错误方法,我已经验证过了。但是我的测试总是失败:间谍没有检测到我的电话。

我总是收到以下错误:

Expected spy error to have been called with [ 'an error occured' ] but it was never called.

我不知道该怎么办。我尝试了我所知道的一切。 起初我认为我的呼叫没有被正确检测到,因为我在模拟我的警报服务,但即使是真实的,它也无法正常工作。

希望能帮到你,先谢谢了!

【问题讨论】:

  • 你能添加更多代码吗?
  • 完成了,如果您需要更多内容,请告诉我:)
  • 你为什么在this.componentthis.fixture中使用this
  • 因为它们是在我配置测试模块的 beforeEach 函数中定义的。

标签: angular unit-testing jasmine spy


【解决方案1】:

似乎this.fixture.whenStable().thencatch 处理程序之前执行。我会使用fakeAsynctick

fit('should call ...', fakeAsync(() => {
  spyOn(component.alert, 'error');
  component.onInputChange('error');
  tick();
  expect(component.alert.error).toHaveBeenCalledWith('an error occured');
}));

Plunker Example

【讨论】:

  • 非常感谢,您的解决方案有效!你有什么理由在 catch 处理程序之前执行“this.fixture.whenStable().then”吗?我虽然“whenstable”方法的目标是在执行某些代码之前等待任何异步任务完成。
  • 我也这么认为。但如果我们深入调查,我们会注意到tick() 正在运行flushMicrotasks。它模拟时间的异步流逝。虽然 whenStable 检查 isStable 状态 this._isStable &amp;&amp; !this.ngZone.hasPendingMacrotasks 但在您的测试期间,isStable 状态没有变化,因为从未调用过 ngZone.onUnstable 事件。使用角度测试总是一个技巧:)
  • 确实,现在看起来很棘手。当调用返回 promise 的函数时从未触发 onUnstable 事件似乎很奇怪。无论如何感谢您的解释:)
猜你喜欢
  • 2020-12-16
  • 2021-03-09
  • 1970-01-01
  • 2014-05-29
  • 2019-07-11
  • 2023-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多