【问题标题】:angular testbed, query by css, find the pseudo element角度测试台,通过css查询,找到伪元素
【发布时间】:2018-08-27 20:46:05
【问题描述】:

我正在使用 TestBed 进行 Angular 2+ 单元测试。 场景,我想验证我的组件,那个伪元素的颜色。

组件.ts

label::before {
        right: 0;
        background-color: red;
      }
@Component({
  selector: 'app-test',
  template: `
    <div><label>a label</label></div>
  `,
  styleUrls: ['./test.component.scss'],
})
export class TestComponent {
  
}

所以我在写单元测试的时候,想验证伪元素背景颜色

  beforeEach(() => {
     fixture = TestBed.createComponent(TestComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

it('should set background color', () => {
  const ele = fixture.debugElement.query(By.css('label::before')).nativeElement; // error here
  // not sure how to use by.css to locate on the pseudo element
  expect(ele.backgroundColor).toBe('....');
});

【问题讨论】:

    标签: css angular unit-testing pseudo-element


    【解决方案1】:

    我建议以不同的方式编写您的测试。

    Fixture 是ComponentFixture&lt;T&gt; 类型,其中T 是您尝试访问的组件。 debugElement 属性有两个您在编写测试时通常感兴趣的属性componentInstancenativeElement

    ComponentInstance 是您的组件ts 文件。从某种意义上说,这是你的类声明。

    NativeElement 顾名思义就是标记或者你的template

    我认为不可能按照您建议的方式进行。

    你可以试试

      const color =  window.getComputedStyle(fixture.debugElement.nativeElement.querySelector('label'), ':after').getPropertyValue('background-color');
    

    这将为您提供 rgb 结果,因此对于红色,它将是 rgb(255,0,0)

    我来自:How to get pseudo element?

    试试这个,看看它是否有效。我们必须访问测试中的窗口元素并不是很好,但它可能会解决您的问题。可能无需访问我建议的窗口 api 就可以创建更好的测试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-25
      • 1970-01-01
      • 1970-01-01
      • 2012-07-08
      • 2017-03-14
      • 2020-05-02
      • 2023-03-18
      • 2013-12-27
      相关资源
      最近更新 更多