javascript 如何使用酶在 div 上模拟鼠标悬停事件以测试反应应用程序?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49934975/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 08:50:14  来源:igfitidea点击:

How to simulate mouse over event on a div using enzyme for testing a react application?

javascriptreactjsjestjsenzyme

提问by Deepank

I have a div that onMouseOverand onMouseLeavetoggles a child div as a dropdown. I want to test the hover event using enzyme.

我有一个 divonMouseOver并将onMouseLeave子 div 切换为下拉列表。我想使用酶测试悬停事件。

The relevant code for the component is:

该组件的相关代码为:

<div className="search-category" onMouseOver={() => toggleDropdown(true)} onMouseLeave={() => toggleDropdown(false)}>
    <div className="search-type">
        ...
    </div>
    {dropdownShown && <SearchMenu searchSections={searchSections} dispatch={dispatch} />}
</div>

The relevant test code is

相关的测试代码是

...
it('should toggle search type dropdown on mouse hover', () => {
    expect(enzymeWrapper.find('.SearchMenu').exists()).toEqual(false);
    enzymeWrapper.find('.search-category').simulate('mouseOver');
    expect(enzymeWrapper.find('.SearchMenu').exists()).toEqual(true);
});
...

.SearchMenuis the className of the SearchMenucomponent.

.SearchMenuSearchMenu组件的类名。

toggleDropdownis a simple function that toggles the dropdownShownflag.

toggleDropdown是一个切换dropdownShown标志的简单函数。

The issue i'm facing is that even after calling .simulate, the expecton the last line returns falsewhen it should return true. The code is working perfectly as I can see the dropdown on the browser and in the element tab of the browser.

我面临的问题是,即使在调用之后.simulateexpect最后一行的返回值false也应该返回true。代码运行良好,因为我可以在浏览器和浏览器的元素选项卡中看到下拉列表。

Please let me know if any more details are required. Any help would be highly appreciated.

如果需要更多详细信息,请告诉我。任何帮助将不胜感激。

回答by Chasing Unicorn

If I have replicated your issue correctly, here is the working demo, of the test cases you were trying to run. I have written a number of test cases using enzyme and jest, and I think this is the right way to do the testing. :)

如果我正确地复制了您的问题,这里是您尝试运行的测试用例的工作演示。我已经使用酶和笑话编写了许多测试用例,我认为这是进行测试的正确方法。:)

Toggle.js

切换.js

import React from "react";

export const SearchMenu = () => <input />;

class Toggle extends React.Component {
  state = { dropdownShown: true };

  toggleDropdown = value => {
    this.setState({ dropdownShown: value });
  };
  render() {
    return (
      <div
        className="search-type"
        onMouseOver={() => this.toggleDropdown(true)}
        onMouseLeave={() => this.toggleDropdown(false)}
      >
        <h1>Hover over me to hide/unhide the input</h1>
        {this.state.dropdownShown && <SearchMenu />}
      </div>
    );
  }
}

export default Toggle;

Toggle.spec.js

Toggle.spec.js

import React from "react";
import { shallow } from "enzyme";
import Toggle from "./Toggle";
import Enzyme from "enzyme";
import { SearchMenu } from "./Toggle";

describe("Toggle Component", () => {
  it("check state", () => {
    const wrapper = shallow(<Toggle />);
    expect(wrapper.find(<SearchMenu />).exists).toBeTruthy();

    // Testing Initial State
    expect(wrapper.state("dropdownShown")).toBe(true);
    wrapper.simulate("mouseleave");

    // Testing state after mouseleave
    expect(wrapper.state("dropdownShown")).toBe(false);

    // Testing state after mouseover
    wrapper.simulate("mouseover");
    expect(wrapper.state("dropdownShown")).toBe(true);
  });
});

回答by Pat Needham

Chasing Unicorn's answer above is almost perfect. Instead of passing mouseoverto wrapper.simulate, it should be mouseenter.

上面追逐独角兽的答案几乎是完美的。而不是传递mouseover给 wrapper.simulate,它应该是mouseenter.

This worked for me:

这对我有用:

  it('sets hoveredOver state to true/fase from mouseenter and mouseleave events', () => {
    const wrapper = shallow(<MyComponent {...defaultProps} />);

    // initial state:
    expect(wrapper.state('hoveredOver')).toBe(false);

    wrapper.simulate('mouseenter');
    expect(wrapper.state('hoveredOver')).toBe(true);

    wrapper.simulate('mouseleave');
    expect(wrapper.state('hoveredOver')).toBe(false);
  });

This is with Enzyme v3.3.0 in my package.json

这是我的 Enzyme v3.3.0 package.json