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");
    });
});
1

1 Answer 1

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'));
});
Sign up to request clarification or add additional context in comments.

3 Comments

Magic. Thanks for help.
Maybe you can help how to test <ng-content></ng-content>? How to bind ng-content property? I using this component in the following way: <card> Content </card> In cart component i use <ng-content></ng-content> tag to display content inside tags.
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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.