我对 Angular @Component
的 Karma Jasmine 测试提示说
ERROR: 'Can't bind to 'ngIf' since it isn't a known property of 'p'.'
当有 that kind of error for the application itself 时,fix 是为了确保您将
BrowserModule
添加到应用程序模块( imports: []
)的 @NgModule()
中的 app.module.ts
中。我确实有那个进口(所以这个问题不是那个 canonical question about "Can't bind to 'ngXXX' since it isn't a known property of '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
或错字,这是另一个 common cause of that error message :<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>
将测试模块配置和对象注入(inject)放在单独的
beforeEach
调用中(如 different Angular testing problem 所建议的那样)没有帮助。
最佳答案
我看到您在 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"
关于Angular Karma Jasmine 测试 "Can' t 绑定(bind)到 'ngIf',因为它不是已知属性”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63813806/