【问题标题】:Angular 2: template not updating in testAngular 2:模板未在测试中更新
【发布时间】:2016-10-07 15:04:04
【问题描述】:

我只是想完成这项工作。

it('should have expected <h1> text', async(() => {
  let fixture = TestBed.createComponent(AppComponent);
  fixture.detectChanges();

  const sectionEl = fixture.debugElement.query(By.css("section"));

  spyOn(fixture.debugElement.componentInstance, "runMe");

  sectionEl.nativeElement.click();
  expect(fixture.debugElement.componentInstance.runMe).toHaveBeenCalled();

  expect(sectionEl.nativeElement.textContent).toBe("changed!");

所以,runMe 函数并没有更改该部分的文本,但间谍显示 runMe 被调用。

【问题讨论】:

  • 您可以编辑您的帖子以包含您的runMe 函数的代码吗?

标签: unit-testing angular angular2-testing


【解决方案1】:

如果没有更完整的示例,很难说。但是对于点击的东西,它通常涉及异步事件处理。因此我们需要等待事件处理完成。在测试中,我们可以通过调用fixture.whenStable 来做到这一点,它会返回一个promise。当 Promise 解决时,我们可以继续测试。

sectionEl.nativeElement.click();
fixture.whenStable().then(() => {
  expect(fixture.debugElement.componentInstance.runMe).toHaveBeenCalled();

  fixture.detectChanges();
  expect(sectionEl.nativeElement.textContent).toBe("changed!");
});

【讨论】:

  • 我之前在自己的项目中尝试过,但它不起作用。我还在 angular 2 quickstart github repo 的克隆本地副本中尝试了类似的方法,但它不起作用。
  • 您可能应该发布一个完整的示例以获得进一步的帮助
  • peeskillet,我正在尝试为此设置一个 Plunkr。你能帮我让 TestBed 在 src/test.spec.ts 中工作吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-08
  • 2021-09-16
  • 2017-02-25
  • 1970-01-01
相关资源
最近更新 更多