Aurelia注入模拟依赖

时间:2016-08-22 16:03:08

标签: javascript testing aurelia aurelia-di

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

尝试测试我想要模拟服务类的组件,特别是get函数,以返回合适的测试数据,并通过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服务类的实例,而不是我注册到容器的模拟实例。

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

或者,如果有替代方法可以实现这一点,那么也可以。

2 个答案:

答案 0 :(得分:3)

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

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

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

答案 1 :(得分:0)

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

使用实际的Api类构造函数作为键而不是字符串&#34; Api&#34;模拟似乎是正确注入的。

&#13;
&#13;
import {Api} from 'services/api';

...

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

相关问题