简体   繁体   中英

How to test subscribe function in angular onInit method?

I have the following component that I want to test:

component:

 constructor(
    private countrystore: Store<CountryAppState>,
    private docstore: Store<DocumentAppState>,
    private formBuilder: FormBuilder,
  ) {}

  ngOnInit() {
    this.getCountryState = this.countrystore.select('selecttimaticCountryState');

    this.getCountryState.subscribe((state) => {
      this.countries = state.response;
    });

Spec file:

describe('TravellerInfoComponent', () => {
  let component: TravellerInfoComponent;
  let fixture: ComponentFixture<TravellerInfoComponent>;

  Object.defineProperty(window, "matchMedia", {
    value: jest.fn(() => { return { matches: true } })
  });

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        StoreModule.forRoot({}),
        EffectsModule.forRoot([]),
        BrowserAnimationsModule,
        HttpClientModule
      ],
      providers: [
        FormsModule
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(TravellerInfoComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

Before I can even write a test I'm getting the following error:

在此输入图像描述

I have looked at similar answers that suggest using the 'of' rxjs operator to simulate an observable, others suggest using a spyOn technique. But I don't quite understand where this should be inserted. Any help for a testing noob would be great.

const countrystore = TestBed.get(Store<CountryAppState>);
spyOn(countrystore, 'select').and.callFake(() => {
  return of(someTestDataYouCreate);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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