Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 在Jasmine中模拟导入的类实例_Angular_Typescript_Jasmine - Fatal编程技术网

Angular 在Jasmine中模拟导入的类实例

Angular 在Jasmine中模拟导入的类实例,angular,typescript,jasmine,Angular,Typescript,Jasmine,我从外部库导入一个类实例,并直接在类成员中使用,如下所示: import { MyClient } from '@foo/bar'; export class DoStuff { public getStuff = () => { return MyClient.fetchThings(); } } 我从中导入该类的库导出该类,如下所示: // my-client.ts class MyClient { //stuff async fetch

我从外部库导入一个类实例,并直接在类成员中使用,如下所示:

import { MyClient } from '@foo/bar';

export class DoStuff {

    public getStuff = () => {
        return MyClient.fetchThings();
    }
}
我从中导入该类的库导出该类,如下所示:

// my-client.ts

class MyClient {
  //stuff
  async fetchThings() {
  }
}

export const myClient =  new MyClient();

-----

// index.ts

export {
  myClient as MyClient,
} from './my-client';
我希望能够在消费应用程序的DoStuff类中删除导入的
MyClient
类实例,但我不确定如何执行

我曾考虑使用,但他们的示例似乎涵盖了您希望在测试所针对的类中新建导入的类的情况

在我的例子中,导入的类已经是一个实例


正确的方法是什么?

正确的方法是使用。不要直接导入实例,而是让Angular注入实例。通过这种方式,服务可以很容易地实现

您可以在
MyClient
上创建一个包装器作为一个可注入服务,并让Angular将其注入
DoStuff
。然后,在测试中,您可以通过
MyClientService

import { MyClientService } from './my-client-service';

export class DoStuff {
    myClientService: MyClientService;

    constructor(myClientService) {
        this.myClientService = myClientService;
    }

    public getStuff = () => {
        return this.myClientService.fetchThings();
    }
}
my-client-service.ts:

import { Injectable } from '@angular/core';
import { MyClient } from '@foo/bar';

@Injectable({
    providedIn: 'root',
})
export class MyClientService {
     myClient: MyClient;

    constructor() {
        this.myClient = MyClient;
    }

    fetchThings() {
        return this.myClient.fetchThings();
    }
}

另请参见

使用服务中的示例。有几种方法,最简单的方法是删除导入并在.spec.ts文件中创建类
class MyClient
。谢谢,我已经更新了我的问题,因为这是利用从Angular外部导入的类,所以我认为我的用例有些不同,我更新了我的问题,因为这是利用从AngularI外部导入的类更新了我的答案。您可以在
MyClient
上编写包装器,然后将其用作可注入服务。