【问题标题】:directive is not a known element in test指令不是测试中的已知元素
【发布时间】:2018-04-15 15:14:24
【问题描述】:

结构是这样的……应该变成npm模块了……

.
./angular.json
./karma.conf.js
./package.json
./tsconfig.json
./demo
./demo/index.html
./demo/main.ts
./demo/test.ts
./demo/tsconfig.app.json
./demo/tsconfig.spec.json
./demo/app
./demo/app.component.html
./demo/app.component.ts
./demo/app.component.spec.ts
./demo/app.module.ts

然后是lib代码

./lib/index.ts
./lib/src/libname.module.ts
./lib/src/libname/libname.component.html
./lib/src/libname/libname.component.ts

该组件适用于ng serve

如果我使用 ng test 运行测试,我会看到 directivename is not a known element 的模板解析错误。

我已尝试将 lib 文件添加到 tsconfig.spec.json 中的文件数组中。
没有成功。

工作的唯一一件事是,我在 app.component.spec.ts 中导入 lib 中的所有组件以及我的 lib 使用的所有组件 并添加将它们添加到 TestBed 声明中。

但我不可能像这样自己将所有组件添加到测试中。

我一定错过了什么。你知道吗?

【问题讨论】:

  • 没有minimal reproducible example 的组件和有问题的测试,真的很难猜。
  • 尝试通过添加一个演示来重现你的测试,你可以克隆这个:stackblitz.com/edit/angular-testing-c25ezq?file=app/…
  • @HDJEMAI 有一个演示,演示就像我写的那样工作。只是在测试中我必须自己声明所有内部组件。当组件中的组件中有组件时,情况不应该如此。您不知道内部组件中使用了哪些组件。在您的链接中,这将是,当您在 NavBarComponent 中使用 NavBarChildComponent 时。然后您必须将 NavBarChildComponent 也放入 Testbed 声明中。
  • 我在这里添加了stackblitz.com/edit/…

标签: angular angular-cli karma-jasmine


【解决方案1】:

我找到了 ;-)

代替

// refine the test module by declaring the test component
TestBed.configureTestingModule({
  declarations: [NavBarComponent, NavBarChildComponent],
  providers: [
    {provide: Location, useValue: location}
    ]
});

我必须使用

// refine the test module by declaring the test component
TestBed.configureTestingModule({
  declarations: [],
  imports: [NavBarModule],
  providers: [
    {provide: Location, useValue: location}
    ]
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-02
    • 1970-01-01
    • 2017-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-07
    相关资源
    最近更新 更多