1

我有一个组件。他的主要作用是包装。

遇到什么麻烦?

当执行组件的方法compileComponents没有属性title时。这就是为什么,正如我所想,在控制台中我看到错误 在此处输入图像描述

问题是:我如何先绑定属性然后运行 ​​compileComponents 方法?

组件模板:

<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('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");
    });
});
4

1 回答 1

2

这是因为您试图在元素存在之前获取它。确定元素title是否*ngIf可见。在检测到更改后尝试将元素移至

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'));
});
于 2016-10-10T13:51:14.387 回答