Jasmine 测试失败 - 但日志表明并非如此

Jasmine Test Fails - But log suggests otherwise

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

我在 TestBed.ConfigureTestingModule 的提供商:

        {provide: FormatService, useClass: FormatServiceMock},

我的模拟Class:

        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() 并知道该函数按预期工作 - 但我仍然是一个谜,为什么我的间谍在一切按预期执行时失败。

需要先调用您的 spyOn 函数然后您的代码调用被监视函数

这应该可以解决问题:

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