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

Angular2 test if component has proper selector

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

例如

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

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

Reflect 元数据被 Angular DI 用于存储和检索装饰器数据。

可以从 class 获取元数据并声明它:

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

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

其中 Reflect.getMetadata('annotations', ...) returns 一个 class 注释数组。

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