簡體   English   中英

Angular Karma Jasmine 測試“無法綁定到 'ngIf',因為它不是已知屬性”

[英]Angular Karma Jasmine test “Can't bind to 'ngIf' since it isn't a known property”

我對 Angular @Component Karma Jasmine 測試抱怨說

錯誤:'無法綁定到'ngIf',因為它不是'p'的已知屬性。'

應用程序本身出現這種錯誤時解決方法是確保將BrowserModule添加到應用程序模塊 ( app.module.ts ) 的@NgModule()中的imports: [] 我確實有那個導入(所以這個問題不是關於“無法綁定到 'ngXXX' 因為它不是 'YYY' 的已知屬性的規范問題的重復)。

這是我的測試設置代碼:

    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調用中(如針對不同的 Angular 測試問題的建議)沒有幫助。

我看到您在TestBed providers包含了 Component 。 組件通常是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,
        ],
...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM