【问题标题】:Mocking imported class instances in Jasmine在 Jasmine 中模拟导入的类实例
【发布时间】:2019-11-16 00:38:55
【问题描述】:

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

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 类实例,但我不确定如何执行。

我曾考虑使用ts-mock-imports,但他们的示例似乎涵盖了您希望在您正在测试的类中新建一个导入类的情况。

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

这里的正确方法是什么?

【问题讨论】:

  • 有几种方法,最简单的方法是删除导入并在您的 .spec.ts 文件中创建 class MyClient
  • 谢谢,我已经更新了我的问题,因为这是使用从 Angular 外部导入的类,所以我认为我的用例有些不同

标签: angular typescript jasmine


【解决方案1】:

正确的做法是使用dependency injection。永远不要直接导入实例,而是让 Angular 注入实例。这样,服务很容易就可以mocked by injecting the mocked service

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

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

export class DoStuff {
    myClientService: MyClientService;

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

    public getStuff = () => {
        return this.myClientService.fetchThings();
    }
}

我的客户服务.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();
    }
}

另见Angular documentation中的示例

【讨论】:

  • 谢谢,我已经更新了我的问题,因为这是使用从 Angular 外部导入的类
  • 我已经更新了我的答案。您可以在 MyClient 上编写一个包装器,然后可以将其用作可注入服务。
猜你喜欢
  • 2021-12-19
  • 2016-03-16
  • 1970-01-01
  • 1970-01-01
  • 2021-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多