角度单元测试spyOn无法检测到我的呼叫

角度单元测试spyOn无法检测到我的呼叫

本文介绍了角度单元测试spyOn无法检测到我的呼叫的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法解决的单元测试有问题.这是我的测试:

I've got a problem with a unit test I can't solve.Here is my test :

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');
     }));
}));

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

And here is the part of the component I'm testing :

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的模拟如下:

For testing purpose, the translateFileService is mocked like this :

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属性表示的警报服务.警报服务不会被嘲笑,它是真正的服务.我已经验证过,实际上是对其错误方法的调用.但是我的测试总是失败:间谍没有检测到我的电话.

The onInputChange method call the alert service representated by the alert property in my component.The alert service is not mocked, it is the real service. The call to it's error method is actually made, I already verified. But my test is always failing : the spy is not detecting my call.

我总是遇到以下错误:

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

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

I don't know what to do. I tried everything I know about.At first I thought my call was not properly detected because I was mocking my alert service, but even with the real one it's not working.

希望您能提供帮助,在此先谢谢您!

I hope you can help, thanks in advance !

推荐答案

似乎this.fixture.whenStable().thencatch处理程序之前执行.我会在tick

Seems this.fixture.whenStable().then is executed before catch handler. I would use fakeAsync with tick

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

柱塞示例

Plunker Example

这篇关于角度单元测试spyOn无法检测到我的呼叫的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 03:15