要编写Angular 6指令的单元测试,可以按照以下步骤进行:
创建一个新的Angular 6项目。
在项目中创建一个指令。例如,创建一个名为CustomDirective
的指令。
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[appCustomDirective]'
})
export class CustomDirective {
constructor(private elementRef: ElementRef) {
this.elementRef.nativeElement.style.backgroundColor = 'red';
}
}
custom.directive.spec.ts
的文件。import { TestBed, ComponentFixture } from '@angular/core/testing';
import { Component, DebugElement } from '@angular/core';
import { By } from '@angular/platform-browser';
import { CustomDirective } from './custom.directive';
@Component({
template: `
`
})
class TestComponent {}
describe('CustomDirective', () => {
let component: TestComponent;
let fixture: ComponentFixture;
let element: DebugElement;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [CustomDirective, TestComponent]
});
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
element = fixture.debugElement.query(By.directive(CustomDirective));
});
it('should apply red background color to the element', () => {
fixture.detectChanges();
expect(element.nativeElement.style.backgroundColor).toBe('red');
});
});
在上述代码中,我们创建了一个TestComponent
,并在其中使用了CustomDirective
。然后,我们创建了一个TestBed
实例,并在其中配置了CustomDirective
和TestComponent
。然后,我们创建了TestComponent
的实例,并查询到使用了CustomDirective
的元素。最后,我们执行了一个断言来验证其背景颜色是否为红色。
ng test
命令来运行单元测试。
上一篇:编写Angular 8中的POST和GET服务的测试用例
下一篇:编写Angular和Java应用时,访问http://localhost:8081/login时出现net::ERR_TOO_MANY_REDIRECTS302错误的问题