Aurelia 注入模拟依赖

Aurelia inject mock dependency

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

尝试测试我想模拟服务 class 的组件,特别是 get 函数,以 return 合适的测试数据,并通过 aurelia 的 DI 容器将此模拟注入到组件中。我遇到问题的 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 服务的实例 class 而不是我注册到容器的模拟实例。

花了最后几个小时试图挖掘任何文档或示例来做这样的事情但没有成功,所以如果有人可以提供帮助,我将不胜感激。

或者,如果有/有替代方法来完成此操作,同样有效。

只是回答我自己的问题,至少是部分回答,如果它对某人有用的话。

通过使用实际的 Api class 构造函数而不是字符串 "Api" 作为键,模拟似乎被正确注入。

import {Api} from 'services/api';

...

      let conf = aurelia.use.standardConfiguration().instance(Api, mockApi);

在使用 aurelia-testing 包测试包含视图和视图模型的标准组件时,我发现更简洁的方法可能是让 Aurelia 创建视图 视图模型,并对所有视图模型依赖项使用模拟classes。

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

此方法允许您使用普通视图模型 class 验证呈现的 HTML,模拟依赖项以控制测试数据。