2021年5月3日星期一

writing unit test for subscription and method inside ngOnInit

I am new to angular testing and trying to write test case for calling a service. In my component my code is as follows.

    ngOnInit() {              this.getDetails();              this.myService.getMode.subscribe(resp => {                this.myMode = resp;              });            }          mode can be of two types "light" or "dark".      getDetails() {       this.myService.getList().subscribe(resp => {            if (resp.length > 0) {              this.dataSource = new MatTableDataSource();            }          }});      }    In my service -            public getList() {      const url = this.baseUrl;      return this._http        .get(url, {          headers: new Headers({ "content-type": "application/json" })        })        .pipe(map(response => response.json()),          catchError(this.handleError));    }             getMode is a observable. My service code is            private mode= new BehaviorSubject("");            getMode = this.mode.asObservable();            modeData(data) {              this.mode.next(data);            }  

I tried writing test for mode and my code is as follows.

  const fakeMyService = {      getMode: of({ mode: "dark" }),    };      beforeEach(      async(() => {        TestBed.configureTestingModule({          declarations: [MyComponent],          providers: [{ provide: myService, useValue: fakeMyService  }],        }).compileComponents();      }),    );      it('should get the mode data', () => {      expect(component.modeData).toEqual('dark')    });    But I am getting following error while running test            TypeError: Cannot read property 'subscribe' of undefined.  Expected undefined to equal 'dark'.  

How can I resolve this and also how can I write a test to test getDetails() to test dataSource?

https://stackoverflow.com/questions/67377816/writing-unit-test-for-subscription-and-method-inside-ngoninit May 04, 2021 at 09:51AM

没有评论:

发表评论