Angular 业力茉莉花测试 "Can't bind to 'ngIf' since it isn't a known property"

Angular Karma Jasmine test "Can't bind to 'ngIf' since it isn't a known property"

我的 Karma Jasmine 测试 Angular @Component 抱怨

ERROR: 'Can't bind to 'ngIf' since it isn't a known property of 'p'.'

当有, the 时,确保您将BrowserModule添加到应用程序模块(app.module.ts)的@NgModule()中的imports: []。我确实有那个进口 (所以这个问题不是 的重复)。

这是我的测试设置代码:

    let component: MyComponent;
    let fixture: ComponentFixture<MyComponent>;

    beforeEach(async () => {
        TestBed.configureTestingModule({
            imports: [
                BrowserModule
            ],
            providers: [
                MyComponent,
                { provide: MyService, useClass: MockMyService }
            ]
        }).compileComponents();
        TestBed.inject(MyService);
        component = TestBed.inject(MyComponent);
        fixture = TestBed.createComponent(MyComponent);
        fixture.detectChanges();
    });

我的 HTML 模板说的是 *ngIf,而不是 ngIf 或拼写错误,这是另一个 :

<div class="self">
    <p *ngIf="isLoggedIn() else selfLogin">Logged in as
        {{getUsername()}}</p>
    <ng-template #selfLogin>
    <button id="login" (click)="login()">login</button>
    </ng-template>
</div>

将测试模块配置和对象注入放在单独的 beforeEach 调用中(如 所建议)没有帮助。

我看到您在 TestBed providers 中包含了该组件。组件通常是 declarations 的一部分。所以,像这样:

    let fixture: ComponentFixture<MyComponent>;
    let component: MyComponent;

    beforeEach(waitForAsync(() => {
        TestBed.configureTestingModule({
            providers: [
                { provide: MyService, useClass: MockMyService }
            ],
            declarations: [
                MyComponent
            ]
        }).compileComponents();
    }));
    beforeEach(() => {
        TestBed.inject(MyService);
        fixture = TestBed.createComponent(SelfComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

您的 else 声明也存在 HTML 格式问题:

<div class="self">
    <p *ngIf="isLoggedIn() else selfLogin">Logged in as
        {{getUsername()}}</p>
    <ng-template #selfLogin>
    <button id="login" (click)="login()">login</button>
    </ng-template>
</div>

应该...

*ngIf="isLoggedIn(); else selfLogin"

由于我没有在声明中包含被测组件,我得到了同样的错误。

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

  beforeEach(
    waitForAsync(() => {
      TestBed.configureTestingModule({
        declarations: [
          MyComponent, // <-What i forgot.
          OtherComponent,
        ],
...