【问题标题】:How to resolve 'calls' does not exist on type '() => any''() => any' 类型不存在如何解决'呼叫'
【发布时间】:2021-08-31 04:23:31
【问题描述】:

测试我的 angular2 应用程序。我尝试设置一个间谍,然后检查它被调用了多少次。我一直收到这个 TS 错误

类型“() => any”上不存在属性“调用”。

我该如何解决这个错误?

describe('ssh Service', () => {
    let ref:SshRefService;

    beforeEach(() => {
        TestBed.configureTestingModule({
            providers: [
                { provide: SshRefService, useClass: refClass },
            ]
        });

    });

    beforeEach(inject([SshRefService], (sshRef:SshRefService) => {
        ref = sshRef
        spyOn(ref, 'getClient').and.returnValue(true)
    }));

    it('should mock an observable', () => {
        //service.list() calls ref.getClient() internally
        expect(service.list('/share')).toEqual(Observable.of(mockFileList));

        expect(ref.getClient.calls.count()).toBe(1);


    });
}); 

【问题讨论】:

  • 尝试做expect((ref.getClient as any).calls.count()).toBe(1);
  • SshRefService 在哪里定义?怎么导入?

标签: typescript jasmine


【解决方案1】:

看起来SshRefService 当前定义了getClient() : any。结果,它正确地抛出了这个错误。发生这种情况是因为模拟过程用 Spy 替换了属性/方法,但 Typescript 无法知道发生了什么。

既然你已经监视了 SshRefService.getClient ,你有两种方法可以测试它是否被调用:

spyOn 返回一个jasmine.Spy 对象,它直接公开了调用属性。您可以将spyOn(ref, 'getClient').and.returnValue(true) 的结果保存在示例对象上,然后像这样进行测试:

expect(getClientSpy.calls.count()).toEqual(1)

首选(可能):您可以在对象本身的方法上运行 expect,如下所示:

expect(ref.getClient).toHaveBeenCalledTimes(1)

【讨论】:

    【解决方案2】:

    与另一个答案类似,但您可以直接向间谍输入

    expect((ref.getClient as jasmine.Spy).calls.count()).toBe(1);
    

    【讨论】:

      猜你喜欢
      • 2019-09-11
      • 2012-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多