【问题标题】:Child component's template does not change, when parent component method is called Angular 2 unit tests当调用父组件方法Angular 2单元测试时,子组件的模板不会改变
【发布时间】:2016-10-20 16:42:27
【问题描述】:

这对我不起作用。请让下面的 Plunkr 工作。

describe("trying a test", () => {
  beforeEach(() => {
    TestBed.initTestEnvironment(BrowserDynamicTestingModule,  platformBrowserDynamicTesting());
    TestBed.configureTestingModule({
      declarations: [myCmp, ChildCmp]
    });
  });

  it("test should work", () => {
    const fixture = TestBed.createComponent(myCmp);
    const div = fixture.debugElement.children[0];
    const childCmp = div.queryAll(By.directive(ChildCmp));

    const divEl = div.queryAll(By.css('div'));

    divEl[0].triggerEventHandler('click', <Event>{});
    fixture.detectChanges();

    expect(childCmp[0].nativeElement.textContent).toBe("updated  value");

  });

}); 

https://plnkr.co/edit/wWJMDi3ZFC6RTSvCw4HH?p=preview

【问题讨论】:

标签: unit-testing angular


【解决方案1】:

这对我来说不再是问题。在大多数情况下(我将在下面概述一个例外),我的父组件和子组件都会在我的真实应用程序代码中更新,尽管我没有更新 Plunkr。

当在模板上单击某些内容时,我只是在被调用的父组件方法上使用 .and.callThrough()。而不是一个简单的间谍。

我确实遇到了 ngFor 渲染的子组件不更新的问题。这是我的另一个问题:Angular 2 unit testing: Make ngFor rendered, child components' templates change?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-25
    • 2020-05-22
    • 2016-11-23
    • 2017-10-10
    • 1970-01-01
    • 2018-05-04
    • 2021-01-05
    相关资源
    最近更新 更多