我正在尝试编写it('should toggle menu', () => {})
单元测试,但很难访问包含toggle方法的指令的属性。
我有一个可重用的组件,它由几个组件/指令组成
ToggleComponent
ToggleDirective
ToggleMenuDirective
这是我的ToggleDirective:
export class ToggleDirective implements OnInit {
@HostBinding('class.toggler-toggle') toggleClass = true;
toggle: boolean;
visible = false;
constructor(private toggler: ToggleService, private el: ElementRef) { }
ngOnInit(): void {
this.toggler.nowToggle.subscribe(toggle => this.toggle = toggle);
}
@HostListener('document:click', ['$event'])
onVoidClick(): void {
this.visible = this.el.nativeElement.contains(event.target) ? !this.visible : false;
this.toggler.setToggleState(this.visible);
}
}
编写单元测试时,我正在使用模拟模板。
使用像这样的模拟模板时,如何在ToggleDirective中访问/测试方法:
import { Component } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { TogglerModule } from './toggler.module';
@Component({
template: `
<toggler>
<toggler-toggle>Toggle</toggler-toggle>
<toggler-menu>
<toggler-item>Sample Item 1</toggler-item>
</toggler-menu>
</toggler>`,
})
class TestComponent {}
describe('TogglerComponent', () => {
beforeEach(() => {
TestBed.configureTestingModule({
imports: [TogglerModule],
declarations: [TestComponent],
})
.compileComponents();
});
it('should create toggler', () => {
expect(TestBed.createComponent(TestComponent).componentInstance).toBeTruthy();
});
it('should toggle menu', () => {
const fixture = TestBed.createComponent(TestComponent);
const component = fixture.componentInstance;
expect(component.visible).toBeFalsy();
component.onVoidClick();
expect(component.visible).toBeTruthy();
});
});
答案 0 :(得分:3)
您可以使用debugElement
的注入器访问指令:
it('should toggle menu', () => {
const fixture = TestBed.createComponent(TestComponent);
const debugElement = fixture.debugElement.query(By.directive(ToggleDirective));
const directive = debugElement.injector.get(ToggleDirective)
expect(directive.visible).toBeFalsy();
directive.onVoidClick();
expect(directive.visible).toBeTruthy();
});