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

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

Angular dependency injection

Определение Provider (useClass, useValue, useFactory ), Injector. Декоратор @Inject, ключ multi: true

13 ноября 2018 г. в Angular

Angular routerLink conditionally

<a [routerLink]="myVar ? '/home' : null" routerLinkActive="is-active">Home</a>
or
<a [routerLink]="myVar ? ['/home'] : []">Home</a>
02 сентября 2019 г. в Angular