【发布时间】:2020-12-28 00:20:18
【问题描述】:
我对 Angular @Component 的 Karma Jasmine 测试抱怨
错误:'无法绑定到'ngIf',因为它不是'p'的已知属性。'
当有that kind of error for the application itself 时,fix 是为了确保您将BrowserModule 添加到您的应用程序模块(app.module.ts)的@NgModule() 中的imports: [] 中。我确实有那个进口
(所以这个问题不是那个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>
将测试模块配置和对象注入放在单独的 beforeEach 调用中(如 different Angular testing problem 的建议)没有帮助。
【问题讨论】:
-
我认为您需要导入
CommonModule而不是BrowserModule,但在测试中不需要导入。您确定您的 HTML 中有*ngIf="..."而不是ngIf=".."吗?另外,尝试在configureTestingModule之后添加compileComponents。
标签: angular jasmine karma-jasmine