Angular2测试组件是否具有适当的选择器

时间:2017-05-25 13:52:45

标签: angular unit-testing typescript jasmine angular-components

Angular2中是否有可能通过单元测试来验证组件选择器?

e.g。

@Component({
    selector: 'my-component',
    template: '<p>test</p>'
})
export class MyComponent {}

....
it(`Component should have selector 'my-component'`, () => {
    expect(component.selector).toBe('my-component');
});

1 个答案:

答案 0 :(得分:2)

Angular DI使用

Reflect元数据来存储和检索装饰器数据。

可以从类中获取元数据并断言它:

  const [componentDecorator] = Reflect.getOwnMetadata('annotations', MyComponentClass);

  expect(componentDecorator.selector).toBe('my-component');

其中Reflect.getMetadata('annotations', ...)返回类注释数组。

这需要加载reflect-metadata core-js/es7/reflect polyfill。此polyfill是Angular的先决条件。