我正在尝试测试具有HTML元素的方法。我正在尝试切换活动班级。它工作正常,但是在运行单元测试时抛出错误。请在下面找到错误。
buttonClick($event){
const clickedElement = $event.target || $event.srcElement;
if( clickedElement.nodeName === "BUTTON" ) {
let isButtonActive = clickedElement.parentElement.querySelector(".active");
// if a Button already has Class: .active
if( isButtonActive ) {
isButtonActive .classList.remove("active");
}
clickedElement.className += " active";
}
}
错误是:TypeError:clickedElement.parentElement.querySelector不是函数
我编写的单元测试是
it('buttonClick chnage the mouse event', () => {
const event = {
srcElement: {
nodeName: 'BUTTON',
parentElement: {
classList: ["btn", "btn-secondary", "btn-sm", "btnTemp", "active"],
className: 'active'
}
},
target: {
nodeName: 'BUTTON',
parentElement: {
classList: ["btn", "btn-secondary", "btn-sm", "btnTemp", "active"],
className: 'active'
}
}
};
component.buttonClick(event);
expect(1+1).toBe(2);
});
答案 0 :(得分:0)
您的代码正在调用querySelector
:
let isButtonActive = clickedElement.parentElement.querySelector(".active");
下面是跟踪信息,它来自:
const clickedElement = $event.target || $event.srcElement;
现在要进行测试:
您通过以下方式调用该函数:
component.buttonClick(event);
事件数据为:
const event = {
srcElement: {
nodeName: 'BUTTON',
parentElement: {
classList: ["btn", "btn-secondary", "btn-sm", "btnTemp", "active"],
className: 'active'
}
},
target: {
nodeName: 'BUTTON',
parentElement: {
classList: ["btn", "btn-secondary", "btn-sm", "btnTemp", "active"],
className: 'active'
}
}
};
这将使clickedElement
等于:
target: {
nodeName: 'BUTTON',
parentElement: {
classList: ["btn", "btn-secondary", "btn-sm", "btnTemp", "active"],
className: 'active'
}
}
然后,返回到:
let isButtonActive = clickedElement.parentElement.querySelector(".active");
您的clickedElement.parentElement
等于:
{
classList: ["btn", "btn-secondary", "btn-sm", "btnTemp", "active"],
className: 'active'
}
该对象没有querySelector()函数,因此没有测试。
一个快速的解决方法是将函数添加到event.target.parentElement中,如下所示:
const event = {
srcElement: {
nodeName: 'BUTTON',
parentElement: {
classList: ["btn", "btn-secondary", "btn-sm", "btnTemp", "active"],
className: 'active'
}
},
target: {
nodeName: 'BUTTON',
parentElement: {
querySelector: (cssSelector) => {},
classList: ["btn", "btn-secondary", "btn-sm", "btnTemp", "active"],
className: 'active'
}
}
};
这将消除该错误。根据您是否要模拟激活的元素,可以决定将返回querySelector: (cssSelector) => {},
。
所有这些,我认为您应该使用真实的DOM和HTML进行测试,而不是伪造您自己的事件。您并没有真正在测试自己认为的测试。一些例子: