gpt4 book ai didi

javascript - Vanilla JS Jest 测试点击事件

转载 作者:行者123 更新时间:2023-12-02 22:19:53 25 4
gpt4 key购买 nike

需要有关通过单击对普通 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( Jest 测试)

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

});

最佳答案

要在设置 (beforeAll) 中实现这一点,您可以使用 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
})
);
});
});

working example

关于javascript - Vanilla JS Jest 测试点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59262223/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com