我在嘲笑 dom 的角度指令测试中遇到了问题操作 API 的 removeChild 或 appendChild 函数。创建指令以添加/删除下拉菜单中的项。
我尝试过嘲笑 DOM 操作 API 的removeChild
或 appendChild
函数与jasmine.createSpyObj
,但不是在嘲笑调用,调用将转到实际函数调用和抛出错误。
it('TestCase: appMenuDropDown Directive',() => {
var rendererMock;
const debugEl: HTMLElement = fixture.debugElement.nativeElement;
rendererMock = jasmine.createSpyObj('rendererMock',['removeChild']);
rendererMock.removeChild(); /*mocking removeChild call*/
const inputEl: HTMLElement = debugEl.querySelector('.list-item');
inputEl.click();
fixture.detectChanges();
expect(rendererMock.removeChild).toHaveBeenCalled();
});
下面是控制台错误。
上下文.js:248 错误类型错误:无法读取未定义的属性"父节点" 在 MenuDropDownDirective../src/app/directives/menu-drop-down.directive.ts.MenuDropDownDirective.clickListener
@Directive({ selector: '[appMenuDropDown]' })
export class MenuDropDownDirective {
@Input() subMenuContainer: ElementRef;
constructor(private el: ElementRef, private renderer: Renderer2) {}
@HostListener('click') clickListener() {
const sourceElement: any = this.el.nativeElement;
const targetElement: any = this.subMenuContainer;
if (sourceElement.children.length > 1) {
this.renderer.removeChild(targetElement.parentNode, targetElement);
} else {
this.renderer.appendChild(sourceElement, targetElement);
}
}
}
it('TestCase: appMenuDropDown Directive appendChild',fakeAsync(() => {
const debugEl: HTMLElement = fixture.debugElement.nativeElement;
const inputEl: HTMLElement = debugEl.querySelector('.list-item');
inputEl.click();
console.log(inputEl.children.length);
expect(inputEl.children.length).toBeGreaterThan(1)
tick();
inputEl.click();
expect(inputEl.children.length).toEqual(1);
}));
@Component({ 模板: <mat-nav-list>
<mat-list-item>
<div class='list-item' appMenuDropDown [subMenuContainer]="subMenuList"
mat-list-item>test1
<span>test2 </span>
</div>
</mat-list-item>
</mat-nav-list>
<mat-nav-list>
<ul #subMenuList>
<li>child1</li>
<li>child2</li>
</ul>
</mat-nav-list>
, 样式: ['mat-list-item { display: block; }']
}(
类 TestMenuDropDownComponent {
}