![](/img/trans.png)
[英]Unit test Angular with Jasmine and Karma, Error:Can't bind to 'xxx' since it isn't a known property of 'xxxxxx'.
[英]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.