单击以获取有关香草JS方法的Jest测试的帮助。
我一直在搜索,但是找不到任何东西。在方法testClick
调用之后,我要测试是否确实单击了每个selected
项目。
const selected = document.querySelectorAll(".selected");
const testClick = (selectedItems) => {
if (selectedItems.length) {
selectedItems.forEach(item => {
item.click();
});
}
}
testClick(selected);
main-test.js(开玩笑的测试)
describe("Unit tests", () => {
let container;
let parent;
let child1;
let child2;
let selectedItems;
beforeEach(() => {
container = window.document.body;
parent = document.createElement("div");
child1 = document.createElement("div");
child2 = document.createElement("div");
child1.classList.add("selected");
child2.classList.add("selected");
parent.appendChild(child1);
parent.appendChild(child2);
container.appendChild(parent);
selectedItems = document.querySelectorAll(".selected");
testClick(selectedItems);
});
it("if 'selectedItems' & testClick() has fired, it should know that each item has been clicked", () => {
// not sure what to do here
});
});
答案 0 :(得分:1)
要在设置(beforeAll
中实现这一目标,您可以将eventListener附加到具有jest.fn()
作为回调的元素上,并断言该函数应该已经用预期的目标调用了
describe("when testClick() has fired", () => {
let clickHandler;
beforeAll(() => {
clickHandler = jest.fn();
document.querySelectorAll("div").forEach(div => {
div.addEventListener("click", clickHandler);
});
// as the `testClick()` is invoked within the application
// you should require the implementation here instead
// of trying to call it within the test
require("./testClick");
});
it("should call the click event listerner for child1", () => {
// not sure what to do here
expect(clickHandler).toHaveBeenCalledWith(
expect.objectContaining({
target: child1
})
);
});
});