要测试Angular中的HostBinding和CSS类,您可以按照以下步骤进行:
import { Component, HostBinding } from '@angular/core';
@Component({
selector: 'app-root',
template: `
`,
styles: [`
.red {
background-color: red;
}
`]
})
export class AppComponent {
@HostBinding('class.blue') isRed = true;
}
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
let component: AppComponent;
let fixture: ComponentFixture;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ AppComponent ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should have "blue" class applied', () => {
const hostElement: HTMLElement = fixture.nativeElement;
expect(hostElement.classList.contains('blue')).toBeTruthy();
});
it('should have "red" class when isRed is true', () => {
component.isRed = true;
fixture.detectChanges();
const hostElement: HTMLElement = fixture.nativeElement;
expect(hostElement.classList.contains('red')).toBeTruthy();
});
it('should not have "red" class when isRed is false', () => {
component.isRed = false;
fixture.detectChanges();
const hostElement: HTMLElement = fixture.nativeElement;
expect(hostElement.classList.contains('red')).toBeFalsy();
});
});
ng test
这样,您就可以测试AppComponent中的HostBinding和CSS类了。第一个测试用例验证了是否应用了"blue"类,第二个和第三个测试用例验证了当isRed为true或false时,是否正确应用或移除了"red"类。