Angular Material单元测试-找不到MatHarness元素



我正在为使用Angular Material的应用程序编写单元测试。

我想确保页面上有一张材料卡片。为此,我使用以下代码:

let loader: HarnessLoader;
let component: LoginComponent;
let fixture: ComponentFixture<LoginComponent>;
let authService: jasmine.SpyObj<AuthService>;
beforeEach(async () => {
authService = jasmine.createSpyObj<AuthService>(['authenticate', 'logout']);
await TestBed.configureTestingModule({
imports: [
RouterTestingModule
],
declarations: [LoginComponent],
providers: [{ provide: AuthService, useValue: authService }]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(LoginComponent);
loader = TestbedHarnessEnvironment.loader(fixture);
fixture.detectChanges();
});
it('should display a material card', async () => {
const card = await loader.getHarness(MatCardHarness);
expect(card).toBeTruthy();
});

但是,这会返回错误:

Error: Failed to find element matching one of the following queries:
(MatCardHarness with host element matching selector: ".mat-card")

这是我的HTML:

<mat-card class="custom-class">
<h2>Sign In</h2>
</mat-card>

我将能够通过向<mat-card>元素添加mat-card类来解决这个问题。但是,如果不手动添加类,它不应该工作吗?我设置测试的方式有什么问题吗?

尝试将MatCardModule导入到TestBed配置中。

import { MatCardModule } from '@angular/material/card';
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [
RouterTestingModule,
MatCardModule,
],
declarations: [LoginComponent],
providers: [{ provide: AuthService, useValue: authService }]
}).compileComponents();
});