如何在角度指令测试中模拟removeChild或appendChild函数调用?

时间:2019-06-19 06:50:16

标签: angular unit-testing karma-jasmine

我在模拟dom时遇到角度指令测试的问题 操纵api的removeChild或appendChild函数。 创建指令以添加/删除项目到下拉菜单。

我尝试模拟DOM操作API的removeChildappendChildjasmine.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();
});

下面是控制台错误。

  

context.js:248错误TypeError:无法读取未定义的属性'parentNode'   在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);
        }
    }
}

2 个答案:

答案 0 :(得分:0)

@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; }']

})

Class TestMenuDropDownComponent {

}

答案 1 :(得分:0)

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);
}));