Angular 2 unit tests beforeEachProvider does not introduce service

I try to test my components in Angular 2, but have problems with it when the component service is not part of its providers.

import {Component} from 'angular2/core';
import {ServiceName} from '../../services/ServiceName';

@Component({
  selector: 'component-name',
  template: `
    <div></div>
  `
})

export class ComponentName {    
  constructor(private ServiceName: ServiceName) {
  }
}

and this is my test:

import {ComponentName} from '<path>';
import {ServiceName} from '<path>';

import {
  iit,
  it,
  ddescribe,
  describe,
  expect,
  inject,
  injectAsync,
  TestComponentBuilder,
  beforeEachProviders,
  fakeAsync,
  tick,
  setBaseTestProviders
} from 'angular2/testing';

beforeEachProviders(() => [
  ServiceName
]);

import {
  TEST_BROWSER_PLATFORM_PROVIDERS,
  TEST_BROWSER_APPLICATION_PROVIDERS
} from 'angular2/platform/testing/browser';

setBaseTestProviders(TEST_BROWSER_PLATFORM_PROVIDERS, TEST_BROWSER_APPLICATION_PROVIDERS);

describe('ServiceName', () => {

  it('should have name property set', injectAsync([TestComponentBuilder], (tcb: TestComponentBuilder) => {
    return tcb.createAsync(ComponentName).then((fixture) => {
      fixture.debugElement.componentInstance.isPanelActive = true;
      fixture.detectChanges();

      var compiled = fixture.debugElement.nativeElement;
      expect(compiled.querySelector('a.yes')).toContainText('Something');
    });
  }));

});

The error I am getting is:

 Failed: No provider for ServiceName! (ComponentName -> ServiceName)
Error: DI Exception

I tried the overrideProvide method, it did not work, and also tried to create a TestComponent inside the test and pass the provider there along with the ComponentName directive.

Does anyone have an idea? Is it not possible to load bootstrap services using a boot file and not use providers in @Component? I thought that was all that was needed in front of each of you.

+4
source share
3 answers
+2

, , . provide :

beforeEachProviders(() => [
  provide(ServiceName, {useClass: ServiceName})
]);
+1

provide:

beforeEachProviders(() => [
  return provide(ServiceName, {useClass: ServiceName})
]);

, return .

+1

Source: https://habr.com/ru/post/1628930/


All Articles