需要帮助与点击的香草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
});
});发布于 2019-12-10 16:00:16
为了在设置(beforeAll)中实现这一点,您可以使用jest.fn()作为回调将eventListener附加到元素,并断言应该已经使用预期的目标调用了函数
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
})
);
});
});https://stackoverflow.com/questions/59262223
复制相似问题