如何在Angular 2中测试* ngFor?

时间:2017-03-03 02:57:12

标签: unit-testing angular karma-jasmine

我是Angular的新手并创建了To-Do Application。我试图在许多地方找到解决方案,即使是Testing documentation 我正在测试一个组件。这带来了来自mongodb的数据,但我已经嘲笑了这些数据。

以下是模板的HTML(使用bootstrap):

<li class="list-group-item" *ngFor="let task of tasks">
    <div class=" task-date">{{task.date}}</div>
</li>

以下是组件代码(我只添加子部分):

export class ShowTaskComponent extends OnInit{

tasks:Task[];

ngOnInit() {
  setInterval(() => {this.refreshTasks()}, 3000);
}

constructor(private appService: AppService, private _router:Router){
  super();
  this.refreshTasks();
}

refreshTasks = function() {

  this.appService.retrieveDataFromServer().subscribe((data: any) => {

    //this.appService.taskArray = data;

    this.tasks = data;

  });

};
}

现在我正在添加测试代码(.spec.ts文件的子部分)...为了解释清楚,所有代码(不包括导入):

  let comp: ShowTaskComponent;
  let fixture: ComponentFixture<ShowTaskComponent>;
  let service: AppService;
  let router: Router;

  let debugTaskTitle: DebugElement[];
  let taskTitles: any[];

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ShowTaskComponent],
      providers: [AppService],
      imports: [....]
    })
      .compileComponents();
  }));

  beforeEach( () => {

    fixture = TestBed.createComponent(ShowTaskComponent);
    service = fixture.debugElement.injector.get(AppService);
    router = fixture.debugElement.injector.get(Router);

    let dummyTasks: any[] = [
      {
        "date": "12 October 2017",
        "title": "Demo task 1",
        "description": "Demo task 1 desc",
        "priority" : "High",
        "_id" : "1"
      },
      {
        "date": "1 January 2018",
        "title": "Demo task 2",
        "description": "Demo task 2 desc",
        "priority" : "Low",
        "_id" : "2"
      }
    ];

    spyOn(service, 'retrieveDataFromServer').and.returnValue(Observable.of<any[]>(dummyTasks));


    fixture = TestBed.createComponent(ShowTaskComponent);
    comp = fixture.componentInstance;
    console.log("----------------------------> comp ", comp);

    debugTaskTitle = fixture.debugElement.queryAll(By.css('div.task-title'));
    console.log("----------------------------> debugTaskTitle ", debugTaskTitle);

    let counter: number = 0;

    for(let title of debugTaskTitle) {
      taskTitles.push(title.nativeElement);
      taskTitles[counter].innerText = dummyTasks[counter].title;
      counter ++;
    }
  });

  //This test fails because taskTitles is undefined!
  it('test whether a correct test has loaded', () =>{

    expect(taskTitles).toBe(["Demo task 1", "Demo task 2"]);
  });

问题来自 debugTaskTitle 。当我尝试使用fixture.debugElement.queryAll(By.css())初始化它时,这是空数组。

我尝试在控制台上打印它(看看长--------&gt;箭头),它是空数组。

组件 comp 的对象已创建并且效果很好。

有谁能告诉我我哪里错了?我提交这项任务的时间已经晚了三天。任何帮助都会很棒。

整个代码位于github repo

另外,当我只运行第一次测试时,我在浏览器上看不到任何内容。它应该在浏览器上显示任务!

这是否意味着* ngFor在.compileComponents();被调用以在第一个beforeEach()内生成CSS和HTML后,不会在页面上填充内容?

1 个答案:

答案 0 :(得分:6)

由于retrieveDataFromServer返回一个Observable,您需要等待异步任务解析。为此,您可以将beforeEach包装在async中,就像它上面的那个一样。然后你需要等待它稳定

fixture = TestBed.createComponent(ShowTaskComponent);
comp = fixture.componentInstance;

fixture.whenStable().then(() => {
    // after something in the component changes, you should detect changes
    fixture.detectChanges();

    // everything else in the beforeEach needs to be done here.
    debugTaskTitle = fixture.debugElement.queryAll(By.css('div.task-title'));
    ...
})