Angular 2单元测试: There is no directive with "exportAs"

标签 angular karma-jasmine ng2-bootstrap

我创建了一个导出引导模式的组件:

@Component({
  selector: 'app-modal',
  templateUrl: './modal.component.html',
  styleUrls: ['./modal.component.scss'],
  exportAs: 'modal'
})

然后在父组件上我按如下方式使用它:

<app-modal #modalHandler="modal"></app-modal>

问题是当我使用 NO_ERROR_SCHEMA 为父组件编写单元测试时,karma 失败并出现以下错误:

There is no directive with "exportAs" set to "modal"

只有在我将模态组件导入 TestBed 中的父组件后,它才会解析。

似乎 NO_ERROR_SCHEMA 并没有消除此错误。无论如何,我可以避免这个错误,而不将子模态导入到我 parent 的单元测试中吗?

最佳答案

It resolves only after i import the modal component to the the parent component in TestBed.

应该导入。因为在 TestBed 中,您刚刚使用父组件创建了一个空模块。在执行此操作时,它也会尝试编译并执行您的父模板。在那里它被蔑视为

<app-modal #modalHandler="modal"></app-modal>

因此它将查找定义为导出为modal的对象。

在测试用例中,由于您的模块为空并且未导入该 app-modal,因此您的父模板无法初始化。

所以你需要

import the modal component to the the parent component in TestBed

这就是 TestBed 的工作原理。您需要导入它,这需要您独立测试您的组件。

注意:

通常我们使用以下行在规范字段本身中创建一个测试模块。

TestBed.configureTestingModule({
});

所以它没有使用您的父组件所在的模块。相反,它是在运行时创建一个测试模块。

关于 Angular 2单元测试: There is no directive with "exportAs",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42898593/

相关文章:

javascript - AngularJS:类型错误:未定义不是本地存储的对象

javascript - 如何在 AngularJS 指令中对 Controller 进行单元测试?

angular - PrimeNG:更改后如何将项目更改为 'pack' 或 'build'?

angular - 将 base64 图像数据数组显示为图像

angular.json include Paths 不适用于 node_modules

angular - 类型 'switchMap' 上不存在属性 'Observable<User>'

angular - 延迟加载。未找到组件工厂。你把它添加到@NgModule.entryComponents 了吗?

javascript - Angular 防护 : Prevent manually accessing a URL

javascript - Karma + Jasmine 测试异步方法

ng-bootstrap - "Angular powered bootstrap"是 "ngx-bootstrap"吗?