【问题标题】:Angular2 testcase shows No provider for NgControlAngular2 测试用例显示 No provider for NgControl
【发布时间】:2023-03-26 14:38:04
【问题描述】:

ng test 显示以下错误,但实际上可以正常工作。

Error: Template parse errors:
    No provider for NgControl ("
      <div class="form-group">
        <label class="control-label">Location</label>
        [ERROR ->]<select class="selectpicker" *ngIf="locations" data-style="btn btn-primary btn-round" title="Select A"): VehicleFormComponent@27:4
    No provider for NgControl ("  <div class="form-group label-floating">
        <label class="control-label">Is Available</label>
        [ERROR ->]<md-slide-toggle [(ngModel)]="isAvailable" color="primary" [ngModelOptions]="{standalone: true}">
       "): VehicleFormComponent@41:4 in src/test.ts (line 25739)
    Expected undefined to be truthy.

我认为这主要是因为在自定义标签中添加了[ngModelOptions]="{standalone: true}"

【问题讨论】:

标签: javascript unit-testing angular karma-jasmine


【解决方案1】:

您是否在 TestBed 模块中添加了对“FormsModule”的引用?

import { FormsModule } from '@angular/forms';

TestBed.configureTestingModule({
  imports: [ FormsModule ]
})
.compileComponents();

【讨论】:

  • 你能重现这个错误吗PhantomJS 2.1.1 (Linux 0.0.0): Executed 39 of 65 (1 FAILED) (0 secs / 1.296 secs) PhantomJS 2.1.1 (Linux 0.0.0) VehicleFormComponent should create FAILED get LocationsService@webpack:///src/app/shared/services/locations.service.ts:9:4173 &lt;- src/test.ts:53695:4196 getInternal
  • 是的,我遇到了这个错误。尝试将 RouterTestingModule 添加到您的 TestBed 导入中。从import {RouterTestingModule} from "@angular/router/testing"; 导入。如果有帮助,请告诉我。
  • 不,不是这种情况。我有LocationStrategy 错误。但似乎只是一些断言失败,而不是编译问题。没有?
  • 是的。仅在运行测试用例时
  • 尝试从 IDE(例如 WebStorm)运行您的测试 - 如果发生异常,它会显示正确的堆栈跟踪。因为错误不清楚 - 据我了解,它可以实例化服务。但没有更多信息(
【解决方案2】:

如果有其他人来这里,也许这会有所帮助。我在构造函数中缺少可选的装饰器:

  constructor(@Optional() @Self() public ngControl: NgControl) {}

【讨论】:

猜你喜欢
  • 2018-11-09
  • 1970-01-01
  • 2017-10-05
  • 2019-01-24
  • 2016-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多