我已经在angular中为按钮标签创建了一条指令,但是我不知道如何在构造函数具有elementRef的情况下测试angular指令。
指令看起来像
import { Directive, ElementRef, Input } from '@angular/core';
@Directive({
// tslint:disable-next-line:directive-selector
selector: '[lstA11yIonButton]'
})
export class LstA11yIonButtonDirective {
@Input() lstA11yLabel: string;
constructor(
private el: ElementRef
) {
el.nativeElement.componentOnReady().then(() => {
this.onShadowReady();
});
}
onShadowReady() {
const button = this.el.nativeElement.shadowRoot.querySelector('button');
button.setAttribute('aria-label', this.lstA11yLabel);
}
}
我编写的测试用例看起来像这样,但没有涵盖代码覆盖率中的代码
import { LstA11yIonButtonDirective } from './lst-a11y-ion-button.directive';
import { ElementRef, Component, DebugElement } from '@angular/core';
import { TestBed, ComponentFixture } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
@Component({
template: `
<button
type="button"
class="button"
lstA11yIonButton
[lstA11yLabel]="'button-label'"
></button>
`
})
class TestComponent {}
describe('Directive: A11yLabelDirective', () => {
let component: TestComponent;
let fixture: ComponentFixture<TestComponent>;
let inputEl: DebugElement;
const elementRef: ElementRef = null;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [LstA11yIonButtonDirective, TestComponent]
});
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
spyOn(elementRef.nativeElement, 'componentOnReady');
inputEl = fixture.debugElement.query(By.all());
});
it('should create component', () => {
expect(component).toBeDefined();
});
it('should set button label', () => {
const debugEl: HTMLElement = fixture.debugElement.nativeElement;
const button: HTMLElement = debugEl.querySelector('button');
});
});
如何用茉莉花在angular 7中测试这种类型的指令?