我创建了一个导出引导模式的组件:
@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/