1

I have a component. Hes main role to be wrapper.

In what trouble?

When method compileComponents executing the component has no property title. Thats why, as i think, in console i see error enter image description here

Question is: How i can first bind property and then run compileComponents method?

Component template:

<div class="card">
    <div *ngIf="title" class="card-header clearfix">
        <h3 class="card-title">{{ title }}</h3>
    </div>
    <div class="card-body">
        <ng-content></ng-content>
    </div>
</div>

Describe section:

describe('CardComponent', () => {

    let comp: CardComponent;
    let fixture: ComponentFixture<CardComponent>;
    let titleEl: DebugElement;  // the DebugElement with the welcome message

    // async beforeEach
    beforeEach( async(() => {
        TestBed.configureTestingModule({
            declarations: [ CardComponent ],
        }).compileComponents(); // compile template and css
    }));

    // synchronous beforeEach
    beforeEach(() => {
        fixture = TestBed.createComponent(CardComponent);
        comp    = fixture.componentInstance;
        titleEl = fixture.debugElement.query(By.css('.card-title'));

        comp.title   = "Greatest title";
        fixture.detectChanges(); // trigger initial data binding
    });

    it('Card check title', () => {
        expect(titleEl.nativeElement.textContent).toContain("Greatest title");
    });
});
Tapakan
  • 328
  • 1
  • 3
  • 15

1 Answers1

2

It's because you are trying to get the element before it even exists. The title determines *ngIf the element is visible. Just move trying to get the element to after you detect changes

beforeEach(() => {
  fixture = TestBed.createComponent(CardComponent);
  comp = fixture.componentInstance;
  // titleEl = fixture.debugElement.query(By.css('.card-title'));

  comp.title = 'Greatest title';
  fixture.detectChanges(); // trigger initial data binding
  titleEl = fixture.debugElement.query(By.css('.card-title'));
});
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
  • Magic. Thanks for help. – Tapakan Oct 10 '16 at 14:13
  • Maybe you can help how to test ? How to bind ng-content property? I using this component in the following way: Content In cart component i use tag to display content inside tags. – Tapakan Oct 10 '16 at 14:18
  • Just make a dummy component in your test that uses the card component. Then just create the dummy component in the test and check the contents of the dummy component. It should have the contents of the card component in it – Paul Samsotha Oct 10 '16 at 14:45