5

我很难理解 TestBed 的工作原理以及如何使用它来模拟数据检索(通过 AngularFire2 即 observables)/推送离线单元测试。如果有人可以提供一个简单的例子来看看它会让事情变得容易得多。

下面是(部分)StateService。然后我将此服务注入另一个组件并打印出 graphModules 名称,例如

图-modules.component.html

<div *ngFor="let module of s.graphModules$ | async"><div class="module-card">{{module.name}}</div></div>

图-modules.component.ts

constructor(public s: StateService){}

状态服务.ts

@Injectable()
export class StateService {

 graphModules$: FirebaseListObservable<any>;
  private auth;

  constructor(public af: AngularFire) {
    af.auth.subscribe(
      latestAuth => {
        this.graphModules$ = af.database.list('/graphModules', {
          query: {
            orderByChild: 'archived',
            equalTo: false
          }
        });
      },
      errors => {
        this.auth = {uid: 'AUTH PROBLEMS'};
        throw 'Problems authenticating';
      }
    );
  }

  saveToDB(key: string, value: any) { 
     this.af.database.list('/graphModules').update(key, value);
     ...
  }
...
}

我想测试的是

1) 给定“graphModules”的模拟/存根,正确数量的 .card-module 将打印到 DOM。

2) 在使用 s.saveToDB() 更新模块之一后,名称在 DOM 中更新

附带说明一下,如果您对我的数据检索“架构”有其他评论,那也是最受欢迎的:)

非常感谢!

编辑:

好的,我发现了如何修复数字 1。测试正确通过。问题 2 尚待回答。规范文件现在看起来像这样:

图-modules.component.spec.ts

class MockStateService {
  public graphModules$: Observable<GraphModule[]>;
  constructor () {
    this.graphModules$ = Observable.of<GraphModule[]>([
      {
        name: 'first',
        ...
      },
      {
        name: 'second',
        ...
      }
    ]);
  }
  updateGraphModule(key: string, value: any) {
    // Not sure what to put here in order to emit new value on graphModules$
  }
}



describe('ModulesComponent', () => {
  let fixture:  ComponentFixture<ModulesComponent>;
  beforeEach(() => {
    this.service = new MockStateService();
    TestBed.configureTestingModule({
      imports: [AppModule],
      providers: [{provide: StateService, useValue: this.service }]
    });
    fixture = TestBed.createComponent(ModulesComponent);
  });

  it('should print out two graphModules', async(() => {
    fixture.whenStable().then(() => {
      fixture.detectChanges();
      const test = fixture.nativeElement.querySelectorAll('.module-card');
      expect(fixture.nativeElement.querySelectorAll('.module-card').length).toBe(2);
    });
  }));


  it('should retrieve new data from observer and update DOM when the first graph-module has been given a new name', async(() => {
    fixture.whenStable().then(() => {
      fixture.detectChanges();
      this.service.updateGraphModule(0, {name: 'new name'});
      // What should I write here to test if the DOM is correctly updated?
    });
  }));
 }));
});
4

0 回答 0