Angular 8-加载垫模块的单元测试问题

如何解决Angular 8-加载垫模块的单元测试问题

我正在尝试为登录组件编写Angular的单元测试。 在组件中,我使用 mat-form-field mat-label mat-icon mat-error 。 他们工作正常。但是当我运行ng test --code-coverage

所有模块都导入/导出到名为material-module的模块。然后将模块导入到登录模块中。
这是我的 login.component.html

<div class="text-center">
  <h1>S'identifier</h1>
</div>
<form class="" [formGroup]="userForm" (ngSubmit)="submit(userForm)">
  <div class="card-body p-6 mb-3">
    <div class="form-group">
      <mat-form-field appearance="outline" class="login-id-form-field">
        <mat-label>Identifiant</mat-label>
        <input
          matInput
          id="email"
          type="email"
          class="login-id"
          [formControl]="userForm.controls['email']"
          [errorStateMatcher]="matcher"
        />
        <mat-icon
          matSuffix
          class="red-icon error-icon"
          *ngIf="
            matcher.isErrorState(userForm.controls['email']) &&
            userForm.controls['email'].errors
          "
          >error</mat-icon
        >
        <mat-icon
          matSuffix
          class="green-icon error-icon"
          *ngIf="!userForm.controls['email'].errors"
        >
          check_circle
        </mat-icon>
        <mat-error *ngIf="userForm.controls['email'].errors">
          Identifiant invalide
        </mat-error>
      </mat-form-field>
    </div>
    <div class="form-group">
      <mat-form-field
        appearance="outline"
        class="login-id-form-field password-form-field"
      >
        <mat-label>Mot de passe</mat-label>
        <input
          matInput
          id="password"
          type="password"
          class="login-id"
          [formControl]="userForm.controls['password']"
          [errorStateMatcher]="matcher"
        />
        <mat-icon
          matSuffix
          class="red-icon error-icon"
          *ngIf="
            matcher.isErrorState(userForm.controls['password']) &&
            userForm.controls['password'].errors
          "
        >
          error
        </mat-icon>
        <mat-icon
          matSuffix
          class="green-icon error-icon"
          *ngIf="!userForm.controls['password'].errors"
        >
          check_circle
        </mat-icon>

        <mat-error *ngIf="userForm.controls['password'].errors">
          Mot de passe invalide ( {{ passwordStrength.label }} )
        </mat-error>
      </mat-form-field>
      <div class="d-flex mt-2" style="height: 24px">
        <mat-error *ngIf="auth.loginError.length && userForm.valid">
          E-mail ou mot de passe incorrect
        </mat-error>
        <div class="ml-auto text-right">
          <a [routerLink]="'reset-password'">Mot de passe oublié ?</a>
        </div>
      </div>
    </div>
    <div class="form-footer mt-5">
      <button
        type="submit"
        class="btn d-block mx-auto primary-strada-btn strada-btn-large"
        [disabled]="!userForm.valid || auth.loggingIn"
      >
        Connexion
      </button>
    </div>
  </div>
</form>

这是我的 login.component.spec.ts

import { TestBed,ComponentFixture } from "@angular/core/testing";
import { ReactiveFormsModule,FormsModule } from "@angular/forms";
import { LoginPageComponent } from "./login-page.component";
// import { LoginPageComponent,User } from "./login-page.component";

describe("Component: Login",() => {
  let component: LoginPageComponent;
  let fixture: ComponentFixture<LoginPageComponent>;

  beforeEach(() => {
    // refine the test module by declaring the test component
    TestBed.configureTestingModule({
      imports: [ReactiveFormsModule,FormsModule],declarations: [LoginPageComponent],});

    // create component and test fixture
    fixture = TestBed.createComponent(LoginPageComponent);

    // get test component from the fixture
    component = fixture.componentInstance;
    component.ngOnInit();
  });

  it("form invalid when empty",() => {
    expect(component.userForm.valid).toBeFalsy();
  });
});

我得到这些错误。

enter image description here

Your global Angular CLI version (10.0.5) is greater than your local
version (8.0.6). The local Angular CLI version is used.

To disable this warning use "ng config -g cli.warnings.versionMismatch false".
14 09 2020 15:01:47.510:INFO [framework:karma-parallel]: sharding specs across 4 browsers
 10% building 2/2 modules 0 active14 09 2020 15:01:53.934:INFO [karma-server]: Karma v4.1.0 server started at http://0.0.0.0:9876/
14 09 2020 15:01:53.936:INFO [launcher]: Launching browsers ChromeHeadless,ChromeHeadless,ChromeHeadless with concurrency unlimited
14 09 2020 15:01:53.943:INFO [launcher]: Starting browser ChromeHeadless
14 09 2020 15:01:53.950:INFO [launcher]: Starting browser ChromeHeadless
14 09 2020 15:01:53.954:INFO [launcher]: Starting browser ChromeHeadless
14 09 2020 15:01:53.964:INFO [launcher]: Starting browser ChromeHeadless
14 09 2020 15:02:10.647:INFO [HeadlessChrome 85.0.4183 (Windows 10.0.0)]: Connected on socket ASC5nD0AuFD0GspSAAAA with id 52943636
14 09 2020 15:02:10.652:INFO [HeadlessChrome 85.0.4183 (Windows 10.0.0)]: Connected on socket QA4STEUC5v4EV55_AAAB with id 27694527
14 09 2020 15:02:10.655:INFO [HeadlessChrome 85.0.4183 (Windows 10.0.0)]: Connected on socket 060bO_di1o_9LmmsAAAC with id 63183944
14 09 2020 15:02:10.658:INFO [HeadlessChrome 85.0.4183 (Windows 10.0.0)]: Connected on socket iAPjmFOsygupfAcZAAAD with id 2553141
HeadlessChrome 85.0.4183 (Windows 10.0.0): Executed 0 of 1 SUCCESS (0 secs / 0 secs)
WARN: 'Spec '[karma-parallel] Add single test to prevent failure should prevent on this shard failing by having successful tests' has no expectations.'
HeadlessChrome 85.0.4183 (Windows 10.0.0): Executed 0 of 1 SUCCESS (0 secs / 0 secs)
WARN: 'Spec '[karma-parallel] Add single test to prevent failure should prevent on this shard failing by having successfHeadlessChrome 85.0.4183 (Windows 10.0.0): Executed 1 of 1 SUCCESS (0.032 secs / 0.004 secs)
HeadlessChrome 85.0.4183 (Windows 10.0.0): Executed 1 of 1 SUCCESS (0.032 secs / 0.004 secs)
HeadlessChrome 85.0.4183 (Windows 10.0.0): Executed 1 of 1 SUCCESS (0.032 secs / 0.004 secs)
HeadlessChrome 85.0.4183 (Windows 10.0.0) WARN: 'Spec '[karma-parallel] Add single test to prevent failure should prevent on this shard failing by having successful tests' has no expectations.'
HeadlessChrome 85.0.4183 (Windows 10.0.0): Executed 1 of 1 SUCCESS (0.032 secs / 0.004 secs)
HeadlessChrome 85.0.4183 (Windows 10.0.0): Executed 0 of 1 SUCCESS (0 secs / 0 secs)
HeadlessChrome 85.0.4183 (Windows 10.0.0) Component: Login form invalid when empty FAILED
        1. If 'mat-label' is an Angular component,then verify that it is part of this module.
        2. If 'mat-label' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("class="form-group">
              <mat-form-field appearance="outline" class="login-id-form-field">
                [ERROR ->]<mat-label>Identifiant</mat-label>
                <input
                  matInput
                  class="login-id"
                  [formControl]="userForm.controls['email']"
                  [ERROR ->][errorStateMatcher]="matcher"
                />
                <mat-icon
        1. If 'mat-icon' is an Angular component,then verify that it is part of this module.
        error properties: Object({ ngSyntaxError: true,ngParseErrors: [ 'mat-label' is not a known element:
        "): ng:///DynamicTestModule/LoginPageComponent.html@7:8,Can't bind to 'errorStateMatcher' since it isn't a known property of 'input'. ("
        "): ng:///DynamicTestModule/LoginPageComponent.html@14:10,'mat-icon' is not a known element:
        2. If 'mat-icon' is a Web  ...
            at <Jasmine>
            at syntaxError (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/compiler/fesm2015/compiler.js:2175:1)
            at TemplateParser.parse (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/compiler/fesm2015/compiler.js:11169:1)
            at JitCompiler._parseTemplate (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/compiler/fesm2015/compiler.js:25541:1)
            at JitCompiler._compileTemplate (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/compiler/fesm2015/compiler.js:25529:61)
            at http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/compiler/fesm2015/compiler.js:25473:1
            at <Jasmine>
            at JitCompiler._compileComponents (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/compiler/fesm2015/compiler.js:25473:1)
            at http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/compiler/fesm2015/compiler.js:25393:1
            at Object.then (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/compiler/fesm2015/compiler.js:2166:27)
            at JitCompiler._compileModuleAndAllComponents (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/compiler/fesm2015/compiler.js:25391:1)
        TypeError: Cannot read property 'userForm' of undefined
            at <Jasmine>
            at UserContext.<anonymous> (http://localhost:9876/_karma_webpack_/webpack:/src/app/login/login-page/login-page.component.spec.ts:26:22)
            at ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone-evergreen.js:359:1)
            at ProxyZoneSpec.push../node_modules/zone.js/dist/zone-testing.js.ProxyZoneSpec.onInvoke (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone-testing.js:308:1)
            at ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone-evergreen.js:358:1)
            at Zone.run (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone-evergreen.js:124:1)
            at runInTestZone (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone-testing.js:561:1)
            at UserContext.<anonymous> (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone-testing.js:576:1)
            at <Jasmine>
HeadlessChrome 85.0.4183 (Windows 10.0.0): Executed 1 of 1 SUCCESS (0.032 secs / 0.004 secs)
HeadlessChrome 85.0.4183 (Windows 10.0.0): Executed 1 of 1 (1 FAILED) (0 secs / 0.255 secs)
HeadlessChrome 85.0.4183 (Windows 10.0.0): Executed 2 of 5 SUCCESS (0 secs / 0.159 secs)
HeadlessChrome 85.0.4183 (Windows 10.0.0): Executed 1 of 1 SUCCESS (0.026 secs / 0.004 secs)
HeadlessChrome 85.0.4183 (Windows 10.0.0) Component: Login form invalid when empty FAILED
        1. If 'mat-label' is an Angular component,'mat-icon' is not a known element:
        2. If 'mat-icon' is a Web  ...
            at <Jasmine>
            at syntaxError (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/compiler/fesm2015/compiler.js:2175:1)
            at TemplateParser.parse (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/compiler/fesm2015/compiler.js:11169:1)
            at JitCompiler._parseTemplate (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/compiler/fesm2015/compiler.js:25541:1)
            at JitCompiler._compileTemplate (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/compiler/fesm2015/compiler.js:25529:61)
            at http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/compiler/fesm2015/compiler.js:25473:1
            at <Jasmine>
            at JitCompiler._compileComponents (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/compiler/fesm2015/compiler.js:25473:1)
            at http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/compiler/fesm2015/compiler.js:25393:1
            at Object.then (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/compiler/fesm2015/compiler.js:2166:27)
            at JitCompiler._compileModuleAndAllComponents (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/compiler/fesm2015/compiler.js:25391:1)
        TypeError: Cannot read property 'userForm' of undefined
            at <Jasmine>
            at UserContext.<anonymous> (http://localhost:9876/_karma_webpack_/webpack:/src/app/login/login-page/login-page.component.spec.ts:26:22)
            at ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone-evergreen.js:359:1)
            at ProxyZoneSpec.push../node_modules/zone.js/dist/zone-testing.js.ProxyZoneSpec.onInvoke (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone-testing.js:308:1)
            at ZoneDelegate.invoke (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone-evergreen.js:358:1)
            at Zone.run (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone-evergreen.js:124:1)
            at runInTestZone (http://localhost:9876/_karma_webpack_/webpack:/node_modules/zone.js/dist/zone-testing.js:5HeadlessChrome 85.0.4183 (Windows 10.0.0): Executed 1 of 1 SUCCESS (0.032 secs / 0.004 secs)
HeadlessChrome 85.0.4183 (Windows 10.0.0): Executed 1 of 1 (1 FAILED) ERROR (0.307 secs / 0.255 secs)
HeadlessChrome 85.0.4183 (Windows 10.0.0): Executed 5 of 5 SUCCESS (0.3 secs / 0.248 secs)
HeadlessChrome 85.0.4183 (Windows 10.0.0): Executed 1 of 1 SUCCESS (0.026 secs / 0.004 secs)

=============================== Coverage summary ===============================
Statements   : 23.48% ( 31/132 )
Branches     : 2.44% ( 1/41 )
Functions    : 10.42% ( 5/48 )
Lines        : 21.14% ( 26/123 )
================================================================================

解决方法

我所需要做的就是在其中导入AngularMaterialModule

    // refine the test module by declaring the test component
    TestBed.configureTestingModule({
      imports: [
        ReactiveFormsModule,FormsModule,AngularMaterialModule],<-------------------------------------------
      declarations: [LoginPageComponent],});```

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-