samedi 22 février 2020

Angular - Test with component dependency

I try to test a component with component dependency, i can't understand what's the way for import this component.

I have this:

import { async, ComponentFixture, TestBed, inject } from '@angular/core/testing';
import { Component, Input, NO_ERRORS_SCHEMA } from '@angular/core';
import { TabsComponent } from './tabs.component';
import { By } from '@angular/platform-browser';

describe('TabsComponent', () => {
    let component: TabsComponent;
    let fixture: ComponentFixture<TabsComponent>;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [TabsComponent, TabComponent],
            schemas: [NO_ERRORS_SCHEMA]
        })
            .compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(TabsComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

    it('should create tabs component', () => {
        expect(component).toBeTruthy();
    });


});

@Component({
    selector: 'tab',
    templateUrl: './tab.component.html',
    styleUrls: ['./tab.component.css']
})

class TabComponent {
    @Input() active: boolean;
    @Input() title: string;
    public value: string = "Hello";
}

Karma show me this error:

TypeError: Cannot set property 'active' of undefined

TabsComponent

import { Component, ContentChildren, QueryList, AfterContentInit } from '@angular/core';

import { TabComponent } from './tab.component';


@Component({
    selector: 'tabs',
    templateUrl: './tabs.component.html',
    styleUrls: ['./tabs.component.css']
})

export class TabsComponent implements AfterContentInit {

    @ContentChildren(TabComponent) tabs: QueryList<TabComponent>;

    select(tab: TabComponent) {
        this.tabs.toArray().forEach(tab => {
            tab.active = false;
        });
        tab.active = true;
    }

    ngAfterContentInit() {

        let actives = this.tabs.filter((tab) => tab.active);

        if (actives.length === 0)
            this.select(this.tabs.first);

    }

}

Aucun commentaire:

Enregistrer un commentaire