How to resolve 'calls' does not exist on type '() => any'

梦想与她 提交于 2020-04-10 08:00:27

问题


Testing my angular2 app. I try and set a spy and then check how many times it has been called. I keep getting this TS error though

Property 'calls' does not exist on type '() => any'.

How Do I resolve this error?

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


    });
}); 

回答1:


It looks like SshRefService currently defines getClient() : any. As a result, it's correctly throwing this error. This is happening because the mocking process replaces the property/method with the Spy, but Typescript has no way of knowing that's taken place.

Since you've spied on SshRefService.getClient , you have two ways to test whether it's been called:

spyOn returns a jasmine.Spy object, which exposes the calls property directly. You can save the result of spyOn(ref, 'getClient').and.returnValue(true) on the example object, and then test that like so:

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

Preferred (probably): You can run expect on the method on the object itself, like so:

expect(ref.getClient).toHaveBeenCalledTimes(1)


来源:https://stackoverflow.com/questions/42259813/how-to-resolve-calls-does-not-exist-on-type-any

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!