繁体   English   中英

角度 - 材料<mat-option>在测试中不可见

[英]Angular - Material <mat-option> not visible in tests

我正在使用 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 serve运行应用程序时,我可以看到带有所有选项的选择框。

<mat-select> 显示选项

但是当我尝试使用 karma 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 { }

请帮我解决这个问题。

您必须触发 MatSelectComponent 的切换以显示您的选项列表,如下所示:

const matSelectComponent = fixture.debugElement.query(By.directive(MatSelect)).componentInstance;
fixture.detectChanges();

现在您可以通过以下方式访问您的选项:

const matOptionComponent = fixture.debugElement.queryAll(By.directive(MatOption));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM