Angular 指令是一种用于改变 DOM 元素行为的机制。单元测试是确保代码质量的一种方法,它通过编写测试用例来验证代码的特定部分是否按预期工作。
假设我们有一个简单的自定义指令 highlight
,它会在元素上添加一个高亮样式。
// highlight.directive.ts
import { Directive, ElementRef, Renderer2, OnInit } from '@angular/core';
@Directive({
selector: '[appHighlight]'
})
export class HighlightDirective implements OnInit {
constructor(private el: ElementRef, private renderer: Renderer2) {}
ngOnInit() {
this.renderer.addClass(this.el.nativeElement, 'highlight');
}
}
// highlight.directive.spec.ts
import { TestBed, ComponentFixture } from '@angular/core/testing';
import { HighlightDirective } from './highlight.directive';
import { Component } from '@angular/core';
@Component({
template: `<div [appHighlight]>Test content</div>`
})
class TestComponent {}
describe('HighlightDirective', () => {
let component: TestComponent;
let fixture: ComponentFixture<TestComponent>;
let divElement: HTMLElement;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [HighlightDirective, TestComponent]
});
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
divElement = fixture.nativeElement.querySelector('div');
fixture.detectChanges();
});
it('should add highlight class to the element', () => {
expect(divElement.classList.contains('highlight')).toBe(true);
});
});
原因:可能是由于 Angular 的变更检测机制没有触发,导致 DOM 元素还没有被渲染出来。
解决方法:确保在 fixture.detectChanges()
之后访问 DOM 元素。如果需要等待异步操作完成,可以使用 fixture.whenStable()
。
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [HighlightDirective, TestComponent]
});
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
fixture.detectChanges();
fixture.whenStable().then(() => {
divElement = fixture.nativeElement.querySelector('div');
});
});
请注意,上述代码和链接仅供参考,实际应用中可能需要根据具体情况进行调整。
领取专属 10元无门槛券
手把手带您无忧上云