How do you inject an angular2 service into a unit test? (RC3)

梦想与她 提交于 2019-12-04 08:47:46

When unit testing, sometimes a certain service causes issues just because it's not being used in a normal environment. You can test to see if it has been called, without having the unit test run through the whole service. Do this by creating a mock class.

describe('route1-detail.component.ts', () => {

class MockActivatedRoute {}

beforeEachProviders(() => [
    {provide: ActivatedRoute, useClass: MockActivatedRoute}
  ]);

it('should instantiate component',
  async(inject([TestComponentBuilder, ActivatedRoute], (tcb:TestComponentBuilder, ar: MockActivatedRoute) => {
  tcb.createAsync(Route1DetailComponent).then((fixture) => {
    expect(fixture.componentInstance instanceof Route1DetailComponent).toBe(true, 'should create Route1DetailComponent');
    console.log(ar);
  });
})));

Notice this part: inject([TestComponentBuilder, ActivatedRoute], (tcb:TestComponentBuilder, ar: MockActivatedRoute. When the code is looking for ActivatedRoute, you are passing it the mock service. Of course if you are specifically trying to unit test ActivatedRoute itself, then creating a mock service defeats that purpose. You might have to add methods or variables to the mock class if it tries to call methods from that service.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!