首页 > 解决方案 > 如何为点击处理程序编写单元测试用例?

问题描述

我现在只能找到元素是否存在。我尝试了模拟功能并模拟手柄点击但无法通过。请指导我如何处理按钮单击。当重定向到为空时,必须处理一个按钮,检查是否调用了名为 buttonOnClickHandler 的函数或调用了 modalHandler。

{isEmpty(redirectTo) ? 
      (<button
        type="button"
        className="help__more-info c-link"
        onClick={buttonOnClickHandler ? buttonOnClickHandler : this.modalHandler}
      ><span className="c-link__icon">
        <img alt={altText || "More Info"} src={icon} />
      </span>
        <span className="c-link__text">
          {buttonText}
        </span>
      </button>) : (
        <a className="c-link" href={redirectTo}>
          <span className="c-link__icon">  
            <img alt={altText || "More Info"} src={icon} />
          </span>
          <span className="c-link__text">
            {linkText || "More Info"}
          </span>
        </a>
      )
    }

我试图写的测试用例如下

describe("When re direction link is defined", () => {
        beforeEach(() => {
            component.setProps({
                redirectTo: ""
            });
        })
        it("Should have 1 button", () => {
            expect(component.find("button").length).toEqual(1);
        });
        it("Should have 1 image", () => {
            expect(component.find("img").length).toEqual(1);
        });
        // describe("When button is clicked", () => {
        //     it('function should have been called', () => {
        //         const modalHandler =  jest.fn();
        //         component = mount(< HelpComponent {...props} />);
        //         component.find('.c-link').at(0).simulate('click');
        //         expect(modalHandler).toHaveBeenCalled();
        //     })
        // })
    });

请参考我共享Js和测试文件的笔。 https://codepen.io/arunkgowda/pen/RwbmmQj

标签: javascriptreactjsjestjsenzyme

解决方案


推荐阅读