首页 > 解决方案 > 通过 spy/karma 模拟服务类时无法读取未定义的属性“doc”

问题描述

我正在尝试通过 Karma 测试我的角度应用程序。我的应用程序已连接到 firebase firestore 数据库。我正在尝试模拟一个集合并使用它来测试我的组件功能。

我正在使用的代码片段如下:

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

我希望代码能够正常工作而没有任何错误。我可能认为我必须重写getSprints我的 MockSprintService 中的方法。有人知道我应该在getSprints()方法中返回或生成什么以使我的 ngOnInit 再次工作吗?帮助将不胜感激。

标签: angularfirebasetestingkarma-jasminespy

解决方案


我看到您正在动态测试模块中导入和初始化 AngularFireModule。这意味着每次运行测试时它实际上都会连接到 Firebase 后端。这通常是一个非常糟糕的主意。如果您的测试用例需要测试编辑或删除条目怎么办?这意味着他们每次都会根据实际数据进行操作。

理想情况下,您希望模拟所有依赖项并尽可能避免导入真实的依赖项(我知道在 Angular 世界中这并不总是可能的)。

我为自己找到的一种解决方案是使用ts-mockito库。它使您可以轻松地模拟类,它通常开箱即用。有一篇我前段时间写的博文,如果你想了解更多:Mocking with ts-mockito

...

回到你的具体例子。看起来您的模拟数据形状与 firebase 服务返回的内容不匹配。

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

您映射每个数据项,并且预计会有一个payload带有对象的doc对象,该对象具有id属性和data()方法。

但是,在您的 MockSprintServce 中,您返回一个带有形状的项目数组的可观察对象:

{
  id: "1",
  name:"TestSprint",
  description:"TestSprint",
  startDate:new Date(2000, 0, 1),
  endDate:new Date(2001, 0, 1),
  isActive:true
}

是根本不匹配。如果您想继续当前设置并使其正常工作,请尝试更改您的

  getSprints(){
    return of(...

[{
  payload: {
    doc: {
      id: '1',
      data: () => ({id: "1", name:"TestSprint", description:"TestSprint", startDate:new Date(2000, 0, 1), endDate:new Date(2001, 0, 1), isActive:true})
    }
  }
}]


推荐阅读