首页 > 解决方案 > 茉莉花测试失败 - 但日志表明并非如此

问题描述

此测试引发错误Expected spy phone to have been called.- 正在调用模拟类方法,如log终端中所示。模拟类没有被任何其他测试调用。我假设我在这里遗漏了一些简单的东西,但我不确定为什么formatSpy测试失败了。

我在 TestBed.ConfigureTestingModule 中的提供者:

        {provide: FormatService, useClass: FormatServiceMock},

我的模拟课:

        export class FormatServiceMock {
             phone() {
               console.log('format phone');
               return;
            }
       }

我的功能正在测试:

    public getPhone(): string {
        if (this.data && this.data.settings) {
            return this.format.phone(this.data.settings.phone);
        } else {
            return '';
        }
    }

我的测试:

        it('should call format service', () => {
            service.data = data;
            service.getPhone();
            let formatSpy = spyOn(format, 'phone').and.callThrough();
            expect(formatSpy).toHaveBeenCalled();
        });

我的输出:

LOG: 'format phone'
HeadlessChrome 79.0.3945 (Mac OS X 10.14.6): Executed 28 of 87 SUCCESS (0 secs / 1.477 secs)
LOG: 'format phone'
HeadlessChrome 79.0.3945 (Mac OS X 10.14.6) EnvironmentService getPhone should call format service FAILED
    Expected spy phone to have been called.

更新 将 MOCK 更改为:

export class FormatServiceMock {
    phone(phone) {
        return phone;
    }
}

并测试:

     it('should call format service', () => {
         service.data = data;
         let result = service.getPhone();
         let formatSpy = spyOn(format, 'phone').and.callThrough();
         expect(result).toEqual('5553335555'); //<--- PASSES
         expect(formatSpy).toHaveBeenCalled(); // <---- FAILS
     })

随着我的破解,我可以删除expect(formatSpy).toHaveBeenCalled()并知道该功能按预期工作 - 但对我来说仍然是一个谜,为什么我的间谍在一切都按预期执行时失败了。

标签: angulartestingjasmine

解决方案


在您的代码调用被监视函数之前,需要调用您的 spyOn函数

这应该解决它:

let formatSpy = spyOn(format, 'phone').and.callThrough();
service.getPhone();
expect(formatSpy).toHaveBeenCalled();

推荐阅读