Angular Karma Jasmine 测试 "Can' t 绑定(bind)到 'ngIf',因为它不是已知属性”

标签 angular jasmine karma-jasmine

我对 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/

相关文章:

angular - 在项目中的所有应用程序上运行 ng test

angularjs - 10000 毫秒内无消息。 Jasmine karma RequireJSS

angular - NullInjectorError : No provider for Storage! ionic 6

angular - 在 VS Code 中使用 Angular/CLI,我可以在构建的同时运行测试吗?

javascript - Jasmine spy 报告功能已被调用时,他们还没有

Angular 2 - 如何模拟组件中调用的服务?

unit-testing - 单元测试Angularjs文件上传 Controller 方法

ruby-on-rails - 访问属性 "invoke"的权限被拒绝

variables - 如果不检查 {{object.field}} 是否存在则出错

javascript - 测试 Angular 1.5 组件 $componentController 未定义