Angular 2:如何使用紧密耦合的父组件和子组件对选项卡组件进行单元化

时间:2017-07-30 15:28:47

标签: javascript angular unit-testing jasmine

我跟着Thoughtram's article创建了一个标签组件。

它基本上创建了两个组件:TabTabs。此处Tabs组件是Tab组件的父/主机,用于将所有选项卡组合在一起。我需要能够对这两个组件进行单元测试。

我想到的测试场景是:

  • Tab必须注入它所依赖的父组件:Tabs
  • 默认情况下必须选择第一个标签。
  • 必须从addTab组件调用Tabs的{​​li>函数Tab
  • 函数selectTab必须在单击相应的选项卡时调用,然后该函数应将选项卡设置为活动状态,将所有其他选项卡设置为非活动状态。
  • 我想还有一些......

问题是我不知道如何测试这些东西以及应该采取什么样的方法。虽然我有角度的文档,但我无法理解这种情况。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

单元测试已经在名称中。您只想测试一个单元。您的Tab组件应单独进行测试。它与您的Tabs组件没有真正的依赖关系。

所以测试看起来像这样:

@Component({
    template: `<tab tabTitle="tabTitle">{{ content }}</tab>`
})
class TestHostComponent {
     @ViewChild(TabComponent) tab: TabComponent;
     content: string = '';
     tabTitle: string = 'foo';
}

describe('TabComponent', function () {
    let fixture: ComponentFixture<TestHostComponent>;
    let comp: TestHostComponent;
    let debugElement: DebugElement;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [ TestHostComponent ]
        }).compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(TestHostComponent);
        comp = fixture.componentInstance;
        debugElement = fixture.debugElement;
        fixture.detectChanges();    // ngOnInit
    });

    it('should create the component', () => expect(comp).toBeDefined() );

    it('should change the title', () => {
        expect(comp.tab.tabTitle).toBe('foobar');
        comp.tabTitle = 'bar';
        fixture.detectChanges();
        expect(comp.tab.tabTitle).toBe('bar');
    });

    it('should change the content', () => {
        comp.content = 'foobar';
        fixture.detectChanges();
        let tabTextContent: string = debugElement.query(By.css('tab')).nativeElement.textContent;
        expect(tabTextContent).toBe('foobar');
    });
});

当然,如果你真的想同时测试两者,你可以用类似的方式进行测试,只需将TestHost的模板改为

即可。
@Component({
     template: `<tabs><tab tabTitle="tabTitle">{{ content }}</tab></tabs>`
});

并调整ViewChilds以及处理ngOnInitAfterViewInit的方式。

但正如我所说,不推荐这样做(您可以在TabsComponent测试中执行此操作,以检查Tabs内部有TabComponentsTabComponent是否正常工作,但不在你的((int(h2)* 60 + int(m2))/24*60) # minutes divided by maximum minutes per day gives a decimal number 中。

只是因为它使测试变得更难和更具体(你必须控制角度生命周期钩子等),你的每个测试集合的大小都变得混乱(这很糟糕,因为你必须改变大多数东西你对组件进行更改的时间),因为它是一个独立的组件,你可以在你希望将它包含在其他地方的场景中运行,并且也必须覆盖它。

希望我能帮到你。