【问题标题】:Angular 2 fixture does not contain styles of component in unit testAngular 2 夹具不包含单元测试中的组件样式
【发布时间】:2017-04-07 11:44:55
【问题描述】:

我遇到以下问题。

这是一个指令的单元测试,指令本身应该简单地改变它所在元素的height 样式属性。我使用一个测试组件作为这个测试的上下文。问题是无论我做什么,样式似乎总是空的。

我在组件中明确设置background-color 只是为了查看它是否在fixture.debugElement 的另一端出现

@Component({
  template: `
    <style>
      .test {
        background-color: white;
      }
    </style>
  <div class="test" appExpandSidebarToBottom></div>`
})
class TestComponent {
  constructor(){}
}



fdescribe('Directive: ExpandSidebarToBottom', () => {

  let fixture;
  let divWithDirective;

  beforeEach(() => {
    fixture = TestBed.configureTestingModule({
      declarations: [ ExpandSidebarToBottomDirective, TestComponent ]
    })
      .createComponent(TestComponent);
    fixture.detectChanges(); // initial binding

    divWithDirective = fixture.debugElement.query(By.css('.test'));
  });

  it('should...', () => {
    console.log(divWithDirective.nativeElement.backgroundColor)
    console.log(divWithDirective.styles)
  });
});

输出是

LOG: undefined
LOG: Object{}

组件中定义的样式在哪里?

【问题讨论】:

    标签: angular angular2-directives angular2-testing


    【解决方案1】:

    根据我的测试,DebugElement.styles 总是返回一个空对象。不知道为什么。对于您的情况,如果您的模板如下所示:

    <div class="test" style="background-color:white;" appExpandSidebarToBottom></div>
    

    然后当你打电话时:

    console.log(divWithDirective.nativeElement.backgroundColor)
    

    您应该能够获得价值white

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-10
      • 2017-10-27
      • 2016-11-23
      • 2017-01-27
      • 2020-08-02
      • 2017-11-19
      • 1970-01-01
      • 2017-06-18
      相关资源
      最近更新 更多