【问题标题】:Unable to locate the function in spec file无法在规范文件中找到函数
【发布时间】:2017-09-04 10:10:56
【问题描述】:

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

我已经正确导入了Example类,但是在Example.spec.ts中也无法调用Example类的函数。

【问题讨论】:

  • Example 是服务还是组件?你是在静态调用吗?

标签: javascript typescript import es6-class angular2-testing


【解决方案1】:

这是一个非常简单的错误。 您是在类函数本身上调用方法,而不是在类的实例类型的对象上。

如果您打算在没有实例的情况下调用该方法,就像您和您的示例代码一样,那么您需要将其标记为静态:

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

另一方面,如果您实际上的意思是它是一个实例方法,您需要创建一个实例来调用该方法:

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

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

最后,值得注意的是,错误文本 id 的表述方式是因为类函数本身的类型写为typeof ClassFunction,而其实例的类型写为只是`ClassFunction

【讨论】:

    猜你喜欢
    • 2014-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-02
    • 2020-07-05
    • 2019-04-11
    相关资源
    最近更新 更多