如何为React中的函数组件编写有关`mouseover`和`mouseleave`的Jest测试用例?

huangapple go评论58阅读模式
英文:

How to write jest test case for moveover and mouseleave for functional component in react?

问题

以下是您提供的代码的翻译部分:

React组件:

我是 jest 测试案例的新手我想要为一个拥有鼠标悬停和鼠标离开事件的 React 组件编写 jest 测试案例我不太确定如何为这些事件编写测试案例我查看了一个StackOverflow的回答它与我的要求非常相似 <https://stackoverflow.com/questions/49934975/how-to-simulate-mouse-over-event-on-a-div-using-enzyme-for-testing-a-react-appli>
根据StackOverflow的回答它是针对类组件编写的但我需要它适用于函数组件

以下是代码

import React, { useState } from "react";

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

const Toggle = () => {
  const [dropdownShown, setDropdownShown] = useState(false);

  return (
    <div
      className="search-type"
      onMouseOver={() => setDropdownShown(true)}
      onMouseLeave={() => setDropdownShown(false)}
    >
      <h1>悬停在我上面以隐藏/显示输入</h1>
      {dropdownShown && <SearchMenu />}
    </div>
  );
};

export default Toggle;

测试案例:

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

describe("Toggle 组件", () => {
  it("检查状态", () => {
    const wrapper = shallow(<Toggle />);
    expect(wrapper.find(<SearchMenu />).exists).toBeTruthy();

    // 测试初始状态
    expect(wrapper.state("dropdownShown")).toBe(true);
    wrapper.simulate("mouseleave");

    // 测试鼠标离开后的状态
    expect(wrapper.state("dropdownShown")).toBe(false);

    // 测试鼠标悬停后的状态
    wrapper.simulate("mouseover");
    expect(wrapper.state("dropdownShown")).toBe(true);
  });
});

在功能组件中,您无法像类组件一样使用 state 属性,因此会出现错误。您需要使用 useState 钩子来管理状态。如果需要测试功能组件中的状态,可以通过模拟事件来触发状态更改并断言状态的值。希望这些信息对您有所帮助。

英文:

I'm newbie for jest test cases, i wanted to write jest test case for a react component which have mouseover and mouseleave event. i'm not sure how to write the test case for those events. I've gone through one stackoverflow answer, it is very similar to my requirement <https://stackoverflow.com/questions/49934975/how-to-simulate-mouse-over-event-on-a-div-using-enzyme-for-testing-a-react-appli>
As per the stackoverflow answer it is written for class component but i need it for functional component.

Here is the code:

import React, {useState} from &quot;react&quot;;

export const SearchMenu = () =&gt; &lt;input /&gt;;

const Toggle = () =&gt; {
  const[dropdownShown, setDropdownShown] = useState(false);

    return (
      &lt;div
        className=&quot;search-type&quot;
        onMouseOver={() =&gt; setDropdownShown(true)}
        onMouseLeave={() =&gt; setDropdownShown(false)}
      &gt;
        &lt;h1&gt;Hover over me to hide/unhide the input&lt;/h1&gt;
        {dropdownShown &amp;&amp; &lt;SearchMenu /&gt;}
      &lt;/div&gt;
    );
}

export default Toggle;

the test case:

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

describe(&quot;Toggle Component&quot;, () =&gt; {
  it(&quot;check state&quot;, () =&gt; {
    const wrapper = shallow(&lt;Toggle /&gt;);
    expect(wrapper.find(&lt;SearchMenu /&gt;).exists).toBeTruthy();

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

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

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

Here i'm getting error ShallowWrapper::state() can only be called on class component

Can anyone help me how to write this test case in functional component?
Thanks! in advance.

答案1

得分: 1

错误消息很清晰。

函数组件没有状态,也没有实例。

useState 不同于组件状态 - React 管理它;它不直接关联到实例。

因此,您可以测试在触发鼠标事件时将呈现什么。

例如:

Toggle.test.tsx:

import React from 'react';
import { shallow } from 'enzyme';
import Toggle, { SearchMenu } from './Toggle';

describe('Toggle Component', () => {
  it('check state', () => {
    const wrapper = shallow(<Toggle />);

    // 测试初始状态
    expect(wrapper.find(SearchMenu).exists()).toBeFalse();

    // 鼠标悬停后测试状态
    wrapper.simulate('mouseover');
    expect(wrapper.find(SearchMenu).exists()).toBeTrue();

    // 鼠标离开后测试状态
    wrapper.simulate('mouseleave');
    expect(wrapper.find(SearchMenu).exists()).toBeFalse();
  });
});

测试结果:

 PASS  stackoverflow/75952818/Toggle.test.tsx (10.562 s)
  Toggle Component
    ✓ check state (29 ms)

------------|---------|----------|---------|---------|-------------------
File        | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
------------|---------|----------|---------|---------|-------------------
All files   |      90 |      100 |      75 |     100 |                   
 Toggle.tsx |      90 |      100 |      75 |     100 |                   
------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        11.354 s
Ran all test suites related to changed files.
英文:

The error message is clear.

> Functional components don’t have state, or an instance.

> useState isn’t the same as component state - React manages that; it’s not directly tied to the instance.

So you can test what will be rendered when triggering the mouse event.

E.g.

Toggle.test.tsx:

import React from &#39;react&#39;;
import { shallow } from &#39;enzyme&#39;;
import Toggle, { SearchMenu } from &#39;./Toggle&#39;;

describe(&#39;Toggle Component&#39;, () =&gt; {
  it(&#39;check state&#39;, () =&gt; {
    const wrapper = shallow(&lt;Toggle /&gt;);

    // Testing Initial State
    expect(wrapper.find(SearchMenu).exists()).toBeFalse();

    // Testing state after mouseover
    wrapper.simulate(&#39;mouseover&#39;);
    expect(wrapper.find(SearchMenu).exists()).toBeTrue();

    // Testing state after mouseleave
    wrapper.simulate(&#39;mouseleave&#39;);
    expect(wrapper.find(SearchMenu).exists()).toBeFalse();
  });
});

Test result:

 PASS  stackoverflow/75952818/Toggle.test.tsx (10.562 s)
  Toggle Component
    ✓ check state (29 ms)

------------|---------|----------|---------|---------|-------------------
File        | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
------------|---------|----------|---------|---------|-------------------
All files   |      90 |      100 |      75 |     100 |                   
 Toggle.tsx |      90 |      100 |      75 |     100 |                   
------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        11.354 s
Ran all test suites related to changed files.

huangapple
  • 本文由 发表于 2023年4月7日 02:47:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/75952818.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定