使用导入的模块对 angular2 组件进行单元测试 [英] Unit Testing angular2 component with imported module

查看:27
本文介绍了使用导入的模块对 angular2 组件进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对使用 angular-material2 的组件编写测试,但是当我将它添加到我的 testModule 声明时,我得到:

I am trying to write a test on a component which uses angular-material2, but when I add it to my testModule declarations I get:

Error: Template parse errors:
    'md-card-title' is not a known element:
    1. If 'md-card-title' is an Angular component, then verify that it is part of this module.
    2. If 'md-card-title' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message.

将 MaterialModule 添加到声明会抛出 `Error: Unexpected module 'MaterialModule' 由模块声明

Adding MaterialModule to the declarations throws `Error: Unexpected module 'MaterialModule' declared by the module

DynamicTestModule' in config/spec-bundle.js (line 24994)

DynamicTestModule' in config/spec-bundle.js (line 24994)

这是我的规范文件的样子:

This is what my spec file looks like:

  beforeEach(() => TestBed.configureTestingModule({
    declarations: [],
    providers: [
      { provide: DataService, useValue: mockDataService },
      { provide: ActivatedRoute, useClass: MockActivatedRoute },
      { provide: Router, useValue: mockRouter },
      CellViewComponent
    ]
  }));

CellViewComponent 添加到声明数组会导致错误抛出.

adding CellViewComponent to the declarations array causes the error to throw.

推荐答案

当您使用 TestBed.configureTestingModule 时,您将从头开始为测试创建一个模块环境.因此,您在实际应用程序中需要什么才能使 CellViewComponent 工作,您还需要在测试模块中对其进行配置.

When you use the TestBed.configureTestingModule, you're create a module from scratch for the test environment. So what ever you would need in the real application for the CellViewComponent to work, you also need to configure it in the testing module.

就您而言,您缺少材料卡组件.在应用程序中,您可能将 MaterialModuleMdCardModule 导入到您的 AppModule 中.所以你需要在测试模块中做同样的事情

In your case, you're missing the Material card component. In the app you probably either imported the MaterialModule or the MdCardModule into your AppModule. So you need to do the same in the testing module

beforeEach(() => TestBed.configureTestingModule({
  imports: [ MaterialModule /* or MdCardModule */ ],
  declarations: [  CellViewComponent ],
  providers: [
    { provide: DataService, useValue: mockDataService },
    { provide: ActivatedRoute, useClass: MockActivatedRoute },
    { provide: Router, useValue: mockRouter },
  ]
}));

这篇关于使用导入的模块对 angular2 组件进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆