【问题标题】:How do I write state case for the state in react useState using Jest如何使用 Jest 在 react useState 中为状态编写状态案例
【发布时间】:2021-01-16 20:11:18
【问题描述】:

我是 Jest 的新手,我正在尝试为状态值编写测试用例,我想更新测试套件中的状态值,任何人都可以提供帮助。谢谢。

例如:我的组件 从'react'导入反应,{useState};

    import Child from './Child';

    function Parent(props) {
      const [isFetching, setState] = useState(false);
      return (
        <div className="parent">
          <h1>Parent</h1>
        {isFetching ? 0 : 1}
        <Child called={setState} />
        { isFetching ? <div>
            <p>from  state true</p>
            <button onClick={clickmefn}>click me</button>
            </div>: null
        }
        </div>
      );
    }

    export default (Parent);

我的测试套件因未找到该元素而失败 wrapper.find('p').text() 无法找到它,因为状态为 false。

import Parent from './Parent';
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });
import { mount, shallow } from 'enzyme';

const setHookState = (newState) => jest.fn().mockImplementation((state) => [
    newState,
    (newState) => {}
 ])

const reactMock = require('react')
describe('ComponentWithHook component', () => {
    let wrapper
    beforeEach(() => {
     wrapper = shallow(<Parent/>)
    });
  it('should render itself', () => {
    const changeCounter = jest.fn();
    const handleClick = jest.spyOn(React, "useState");
    handleClick.mockImplementation(isFetching => [isFetching, changeCounter]);
    
    expect(wrapper.find('p').text()).toBe('from  state true');
  })

})

【问题讨论】:

  • 我建议避免模拟状态。相反,只需在组件上进行交互,使其进入该状态。我知道你在使用酶,但是看看 React 测试库的原则,我认为它们是有道理的:testing-library.com/docs/guiding-principles
  • 组件上的交互?如果可能的话,我可以举个例子吗?
  • 如中,模拟按钮点击等,然后测试显示“这样那样的文本”。
  • 是的,我们可以这样做,但是我不想在视图中显示按钮和测试,是否可以只在测试文件中添加它自己?
  • 测试组件的内部结构非常容易出错。您应该考虑编写集成测试,而不是意味着您渲染您的组件,与之交互并将 DOM 与预期的内容进行比较。另请参阅react testing library 的作者blog of kentcdoddsrecommended 作为用于测试反应组件的工具。特别是this

标签: reactjs unit-testing jestjs enzyme


【解决方案1】:

我建议尽可能进行更真实的测试,您可以在不使用额外库的情况下完成测试,只需使用 react-dom 和 react-dom/test-utils。

import React from "react";
import { render, unmountComponentAtNode } from "react-dom";
import { act } from "react-dom/test-utils";
import Parent from './Parent';

    
describe("App Tests", () => {
  let container = null;

  beforeEach(() => {
    container = document.createElement("div");
    document.body.appendChild(container);
  });

  afterEach(() => {
    unmountComponentAtNode(container);
    container.remove();
    container = null;
  });

  it("should render itself", () => {
   act(async () => {
      render(
        <Parent/>,
        container
      );
    });

    const childElement = container.querySelector(`.child-element`); // get the child element
    act(() => {
      childElement.dispatchEvent( // distpach the action to update the state
       new MouseEvent("click", { bubbles: true })
     );
   });
    expect(container.querySelector('p')).toBeTruthy();
    expect(container.querySelector('p').textContent).toBe("from  state true");
  });
});

编辑://在这里您可以找到更多信息,https://reactjs.org/docs/testing-recipes.html

【讨论】:

    猜你喜欢
    • 2020-09-12
    • 1970-01-01
    • 1970-01-01
    • 2020-07-08
    • 2019-10-17
    • 1970-01-01
    • 1970-01-01
    • 2020-04-29
    • 1970-01-01
    相关资源
    最近更新 更多