Unable to locate the function in spec file

907 Views Asked by At

Example.ts

export class Example{

public async initService(Id): Promise<any> {

//promise logic

    }
}

Example.spec.ts

 //imported Example class correctly

    describe('testing', async () =>{
       it('InitService test call', async ()=>{
            let x = await Example.initService(id:any) //this line displays error as initService does not exist on type 'typeof AnnounceService'
    });
});

I have imported the class Example correctly but then too unable to call the function of Example class in the Example.spec.ts.

1

There are 1 best solutions below

0
On

This is a very simple mistake. You're calling the method on the class function itself, not on an object of the class's instance type.

If you intend to call the method without an instance, as you do and your sample code, then you need to mark it as static:

export class Example {
   static async initService(Id) {}
}

If, on the other hand, you actually mean for it to be an instance method you need to instead create an instance in order to call the method:

export class Example {
   async initService(Id) {}
}

 describe('testing', async () => {
    it('InitService test call', async () => {
      const x = await new Example().initService(1);
    });
 });

Finally, it is worth noting that the error text id phrased in the manner it is because the type of the class function itself is written as typeof ClassFunction whereas the type of its instances is written as just `ClassFunction