我正在为使用 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>
元素来解决此问题。但是它不应该在不手动添加类的情况下工作吗?我设置测试的方式有什么问题吗?
答案 0 :(得分:0)
您可以使用忽略架构
await TestBed.configureTestingModule({
imports: [
RouterTestingModule
],
declarations: [LoginComponent],
schemas: [NO_ERRORS_SCHEMA],
providers: [{ provide: AuthService, useValue: authService }]
})
或者您仍然可以将 mat card 模块导入到您的测试中。
答案 1 :(得分:0)
尝试将 MatCardModule 导入您的 TestBed 配置。
import { MatCardModule } from '@angular/material/card';
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [
RouterTestingModule,
MatCardModule,
],
declarations: [LoginComponent],
providers: [{ provide: AuthService, useValue: authService }]
}).compileComponents();
});