user7890278
user7890278

Reputation:

Unit test for Component within component Angular 4

I am using Tab control using the thoughtram blog post. Here is the plnkr for the same.

I was trying to create a unit test cases for the Tabs component which internally using Tab Component. And not sure how I can do it in Angular 4 with Jasmine.

How I can inject Tab in Tabs Component so that I could cover its ngAfterContentInit() and selectTab() methods?

Thanks..

Upvotes: 1

Views: 1785

Answers (1)

Mukesh Rawat
Mukesh Rawat

Reputation: 2097

I would unit test tabs by wrapping into a test component and run assertion on that, like below:

@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();
  });
});

Hope it would help!

Upvotes: 1

Related Questions