我正在使用Material组件开发Angular 9。我想在mat-select组件中显示一些值。
下面是app.component.html
<h2> Angular - Material </h2>
<mat-form-field>
<mat-label>Type</mat-label>
<mat-select >
<mat-option value="string">Small text</mat-option>
<mat-option value="number">Number</mat-option>
<mat-option value="date">Date</mat-option>
</mat-select>
</mat-form-field>
<hr>
我的app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
title = 'angular-playground';
}
当我使用 ng服务运行应用程序时,我会看到带有所有选项的选择框。
但是,当我尝试使用业力 ng test 测试该组件时,选择框内没有任何选项。我尝试检查HTML DOM,但在select中看不到任何选项标签,并且控制台中没有错误。
app.component.spec.ts
import { TestBed, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
import { MatFormFieldModule } from '@angular/material/form-field';
import {MatSelectModule} from '@angular/material/select';
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule, MatFormFieldModule, MatSelectModule
],
declarations: [
AppComponent
],
}).compileComponents();
}));
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});
});
这是一个非常基本的角度应用程序,我有一个仅带有选择框的简单组件。不知道为什么它没有在测试中显示选项。
下面是我的app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatFormFieldModule } from '@angular/material/form-field';
import {MatSelectModule} from '@angular/material/select';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
MatFormFieldModule,
MatSelectModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
请帮助我。
答案 0 :(得分:0)
您必须触发MatSelectComponent的切换才能显示这样的选项列表:
const matSelectComponent = fixture.debugElement.query(By.directive(MatSelect)).componentInstance;
fixture.detectChanges();
现在,您可以通过以下方式访问您的选项:
const matOptionComponent = fixture.debugElement.queryAll(By.directive(MatOption));