繁体   English   中英

Aurelia注入模拟依赖

[英]Aurelia inject mock dependency

我有这个aurelia组件用于向用户显示提要,该提要依赖于称为Api的自定义API服务类来获取提要。 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服务类的实例,而不是我的已注册到容器的模拟实例。

花了最后几个小时尝试找出任何文档或示例来完成类似的事情而没有成功,所以如果有人可以提供帮助,我将不胜感激。

或者,如果有/有其他方法可以完成此任务,那么也将同样有效。

当使用aurelia-testing测试由视图和视图模型组成的标准组件时,我发现一种更干净的方法可能是让Aurelia创建视图视图模型,并对所有视图使用模拟类。模型依赖性。

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,模拟依赖项来控制测试数据。

仅回答我自己的问题(至少部分回答)是否对某人有用。

通过使用实际的Api类构造函数作为键而不是字符串“ Api”作为键,该模拟似乎已正确注入。

 import {Api} from 'services/api'; ... let conf = aurelia.use.standardConfiguration().instance(Api, mockApi); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM