【问题标题】:Unit test for Component within component Angular 4组件Angular 4中组件的单元测试
【发布时间】:2018-01-01 14:42:11
【问题描述】:

我正在通过thoughtram 博客文章使用 Tab 控件。这是相同的plnkr。

我试图为内部使用选项卡组件的选项卡组件创建单元测试用例。并且不知道如何在Angular 4 和Jasmine 中做到这一点。

如何在 Tabs 组件中注入 Tab 以便覆盖其 ngAfterContentInit() 和 selectTab() 方法?

谢谢..

【问题讨论】:

  • 我不知道这个帖子是否有帮助。让我知道..stackoverflow.com/questions/35975879/…
  • 有没有理由不单独测试Tab 组件和Tabs 组件?我认为这将是一个更好的选择
  • 为了测试Tabs 组件,您还必须通过Tab 集合。这就是我的问题;我如何将它传递给Tabs 组件。

标签: angular unit-testing jasmine


【解决方案1】:

我会通过包装到一个测试组件中来对tabs 进行单元测试并对其运行断言,如下所示:

@Component({
  template: `
  <tabs>
      <tab title="tab-1"></tab>
      <tab title="tab-2"></tab>
  </tabs>`,
})
class TestTabsComponent { }


describe("Component: Tabs", () => {
  let component: TestTabsComponent;
  let fixture: ComponentFixture<TestTabsComponent>;

  beforeEach(() => {
    TestBed
      .configureTestingModule({
        declarations: [
          TabsComponent,
          TabComponent,
          TestTabsComponent,
        ],
      });

    fixture = TestBed.createComponent(TestTabsComponent);
    component = fixture.componentInstance;
  });

  it('should have tab title', async(() => {
    fixture.detectChanges();
    let compiled = fixture.debugElement.queryAll(By.css('tab'));
    expect(compiled[0].nativeElement.title).toBe('tab-1');
    expect(compiled[1].nativeElement.title).toBe('tab-2');
  }));

  afterEach(() => {
    fixture.destroy();
  });
});

希望对您有所帮助!

【讨论】:

  • 谢谢.. 之后我得到了 100% 的覆盖率。
猜你喜欢
  • 2018-05-01
  • 2021-01-05
  • 2017-10-10
  • 2019-03-26
  • 1970-01-01
  • 1970-01-01
  • 2018-01-07
  • 2017-12-15
  • 1970-01-01
相关资源
最近更新 更多