首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Vanilla JS Jest测试点击事件

Vanilla JS Jest测试点击事件
EN

Stack Overflow用户
提问于 2019-12-10 15:27:48
回答 1查看 1K关注 0票数 1

需要帮助与点击的香草JS方法的Jest测试。我已经到处找了,但是找不到任何东西。在testClick调用该方法之后,我想测试一下是否确实单击了每个selected项。

代码语言:javascript
复制
const selected = document.querySelectorAll(".selected");
const testClick = (selectedItems) => {
    if (selectedItems.length) {
        selectedItems.forEach(item => {
            item.click();
        });
    }
}
testClick(selected);

main-test.js (jest测试)

代码语言:javascript
复制
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
    });

});
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-12-10 16:00:16

为了在设置(beforeAll)中实现这一点,您可以使用jest.fn()作为回调将eventListener附加到元素,并断言应该已经使用预期的目标调用了函数

代码语言:javascript
复制
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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59262223

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档