javascript - Aurelia 注入(inject)模拟依赖

标签 javascript testing aurelia aurelia-di

我有一个 aurelia 组件,用于向用户显示提要,该组件依赖于一个名为 Api 的自定义 API 服务类来获取提要。 Api 类有一个 get() 函数,该函数又使用 HttpClient 来获取数据。

尝试测试组件,我想模拟服务类,特别是 get 函数,以返回合适的测试数据,并通过 aurelia 的 DI 容器将此模拟注入(inject)到组件中。我在 DI 部分遇到了麻烦。

这是组件js文件的相关部分

import {bindable, inject} from 'aurelia-framework';
import {Api} from 'services/api';

@inject(Api)
export class Feed {
  events = null;

  constructor(api) {
    console.info('feed.js constructor, api:', api)
    this.api = api;
  }

以及我测试中的相关代码

  beforeEach(done => {
    ...
    let mockApi = new Api();
    spyOn(mockApi, 'get').and.returnValue(mockGetResponse);

    const customConfig = (aurelia) => {
      let conf = aurelia.use.standardConfiguration().instance("Api", mockApi);
      console.info('Registering Api:', conf.container.get("Api"));
      return conf;
    }

    const ct = new ComponentTester();
    ct.configure = customConfig;

    sut = ct.withResources('activityfeed/feed');
    sut.inView('<feed username.bind="username"></feed>')
        .boundTo({username: TEST_USER});

    sut.create(bootstrap).then(() => {
      done();
    });
  });

据我所知,这段代码实际上按照我的预期方式工作。创建组件时,我的 customConfig 函数被调用,mockApi 实例被记录到控制台。

然而,在引导过程的后期,组件构造函数仍然接收实际 Api 服务类的实例,而不是注册到容器的模拟实例。

在过去的几个小时里尝试挖掘任何文档或示例来执行此类操作,但没有成功,因此如果有人可以提供帮助,我将不胜感激。

或者,如果有其他方法可以实现这一点,也同样有效。

最佳答案

当测试由 View 和 View 模型组成的标准组件时,使用aurelia-testing包中,我发现更简洁的方法可能是让 Aurelia 创建 View 和 View 模型,并为所有 View 模型依赖项使用模拟类。

export class MockApi {
  response = undefined;

  get() { return Promise.resolve(this.response) }
}

describe("the feed component", () => {
  let component;
  let api = new MockApi();

  beforeEach(() => {
    api.response = null;

    component = StageComponent
      .withResources("feed/feed")
      .inView("<feed></feed>");

    component.bootstrap(aurelia => {
      aurelia.use
        .standardConfiguration();

      aurelia.container.registerInstance(Api, api);
    });
  });

  it("should work", done => {
    api.response = "My response";

    component.create(bootstrap).then(() => {
      const element = document.querySelector("#selector");
      expect(element.innerHTML).toBe("My response, or something");

      done();
    });
  });
});

此方法允许您使用普通 View 模型类验证渲染的 HTML,模拟依赖项来控制测试数据。

关于javascript - Aurelia 注入(inject)模拟依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39084036/

相关文章:

testing - 什么是冒烟测试?

javascript - Aurelia 未脏检查功能导致 HTML 类属性绑定(bind)

android - 如何在 Android 中填充测试数据库?

javascript - 在 JavaScript 中找到第一个字母时如何拆分字符串?

javascript - 如何更改特定的 jQuery dataTables 单元格值

javascript - 如何从javascript中的字符串中获取月份

android - 单元测试 Glide : make sure ImageView has correct image

javascript - 使用计算的 aurelia 搜索过滤在渲染 View 时会导致问题

aurelia - Aurelia 中的 <compose> 和 <require> 有什么区别?

javascript - Javascript 中的照片标记