首页 > 解决方案 > Angular 2+:如何测试通过 :host 选择器应用的宿主元素样式?

问题描述

fixture.debugElement.nativeElement.style我正在尝试测试在组件的宿主元素上应用的样式,但如果它们通过样式表中的选择器应用,看起来应用的样式不会显示在其中:host

假设我们有按钮组件:

@Component({
  selector: 'test-button',
  templateUrl: './button.component.html',
  styleUrls: ['./button.component.scss'],
})
export class ButtonComponent implements OnInit {
  constructor() {}

  ngOnInit() {}
}

button.component.scss 包含:

:host {
  border-radius: 4px;
}

在我们的规范文件中:

describe('ButtonComponent', () => {
  let fixture: ComponentFixture<TestApp>;
  let buttonDebugElement: DebugElement;
  let testComponent: TestApp;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ButtonModule],
      declarations: [TestApp],
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(TestApp);
    testComponent = fixture.componentInstance;
    buttonDebugElement = fixture.debugElement.query(By.css('test-button'));
  });

  describe('styles', () => {
    let hostElement: HTMLElement;

    beforeEach(() => {
      hostElement = buttonDebugElement.nativeElement;
    });

    it('should have border-radius of 4px', () => {
      // hostElement.style.borderRadius is "" instead of "4px"
      expect(hostElement.style.borderRadius).toBe('4px');
    });
  });
});

/** Test App. */
@Component({
  selector: 'test-app',
  template: `
    <test-button>
      {{ textContent }}
    </test-button>
  `,
})
class TestApp {
  textContent: string = 'Hi test-button!';
}

但如果我使用HostBinding('style.borderRadius'),它会按预期工作。

有没有办法测试通过 :host 选择器应用的样式?如果没有,@HostBinding 是测试应用于宿主元素的样式的唯一方法吗?

标签: angularunit-testing

解决方案


推荐阅读