mercredi 29 mai 2019

Cannot read property 'doc' of undefined when mocking service class through spy/karma

I am trying to test my angular application through Karma. My application is connected to a firebase firestore database. I am trying to mock a collection and use this to test my component functions.

The code snippets that I am using are the following:

sprint.service.ts:

export class SprintService {

  getSprints() {
    return this.firestore.collection('sprints').snapshotChanges();
  }
  constructor(private firestore: AngularFirestore) { }
}

sprints.component.ts

sprints : Sprint[];

constructor(private sprintService: SprintService) { }

ngOnInit() {
    this.sprintService.getSprints().subscribe(data => {
      this.sprints = data.map(e => {
        return {
          id: e.payload.doc.id, //HERE IT ERRORS
          ...e.payload.doc.data()
        } as Sprint;
      })
    });
  }

sprints.component.spec.ts

//Mock class
class MockSprintServce
{
  getSprints(){
    return of([
      {id: "1", name:"TestSprint", description:"TestSprint", startDate:new Date(2000, 0, 1), endDate:new Date(2001, 0, 1), isActive:true},
      {id: "2", name:"TestSprint2", description:"TestSprint2", startDate:new Date(2000, 0, 1), endDate:new Date(2001, 0, 1), isActive:false},
    ])
    }
}

beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ FormsModule, AngularFireModule.initializeApp(environment.firebase) ],
      declarations: [ ArchivedUserstoriesComponent,SprintDetailComponent, SprintsComponent, UserDetailComponent, UsersComponent, UserstoriesComponent, UserstoryDetailComponent ],
      providers: [AngularFirestore, {provide: SprintService, useClass: MockSprintServce}]
    })
    .compileComponents();
  }));

beforeEach(() => {
    app.sprints = [
      {id: "1", name:"TestSprint", description:"TestSprint", startDate:new Date(2000, 0, 1), endDate:new Date(2001, 0, 1), isActive:true},
      {id: "2", name:"TestSprint2", description:"TestSprint2", startDate:new Date(2000, 0, 1), endDate:new Date(2001, 0, 1), isActive:false},
    ]
  });


it(`should return all Sprints`, async(() => {

    //arrange
    let getSpy = spyOn(mockSprintServiceObject, 'getSprints').and.returnValue({ subscribe: () => {} });

    //act
    app.ngOnInit({});

    //assert
    expect(getSpy).toHaveBeenCalled();
    expect(getSpy).toContain(app.sprints[1]);
  }));

I want the code to be working without any errors. I probably think i have to rewrite the getSprints method in my MockSprintService. Does anybody know what i should return or generate in the getSprints() method to make my ngOnInit work again? Help would be appreciated.

Aucun commentaire:

Enregistrer un commentaire