Angular Testing. Override component's service

component.ts

@Component({
  selector: 'my-component',
  template: '',
  providers: [ComponentService], // <=== component's service
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class MyComponent implements OnInit, OnDestroy { ... }

angular error during cleanup of component

component.spec.ts


  const windowMock = {
    location: {
      href: null
    }
  };

  const ComponentServiceSpy = {
    ...jasmine.createSpyObj<ComponentService>('ComponentService', [
      'init',
      'orderDomains',
      'destroy',
      'ngOnDestroy' // <=== angular error during cleanup of component
    ]),
    state$: of({
      ok: {
        preloader: false,
        disabled: true,
      },
      cancel: {
        disabled: false,
      },
    } as FormButtonsState),
  };  

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        ReactiveFormsModule,
        RouterTestingModule,
        MyTestModule,
      ],
      providers: [
        { provide: ModalService, useValue: modalServiceSpy },
        { provide: WINDOW, useValue: windowMock }
      ],
      declarations: [MyComponent, MyComponentChildrenMockComponent],
    })
      .overrideProvider(ComponentService, { // override
        useValue: ComponentServiceSpy,
      })
      .compileComponents();
  }));

Похожие записи

let-* $implicit in Angular template

Синтаксис let-* позволяет объявить переменную в шаблоне , использования ключа $implicit позволяет устанавливать значение по-умолчанию для объявленной переменной.

29 августа 2018 г. в Angular

RxJs Subjects

Выдержки из доклада Андрея Алексеева (Tinkoff) про RxJs (Subject, Behaviour Subject, Replay Subject, Async Subject). Применение в Angular.

Angular. Когда не надо отписываться в RxJS?

В async pipe за вас отпишется Angular. Во всех остальных случаях лучше отписываться самостоятельно. Допускается не отписываться в потоках, где будет гарантировано вызван complete.