如何测试与酶/开玩笑中的反应中设置状态的组件

发布于 2025-02-12 09:31:01 字数 1122 浏览 0 评论 0原文

假设我需要测试此组件。它通过道具获得了状态和设定者。测试应该是什么样的?

component.jsx

export function Component({ isShowing, setShow }) {
  return (
    <>
      <button
        onClick={() => {
          setShow(!isShowing);
        }}
      >
        Toggle
      </button>
      {isShowing && <h1>Showing</h1>}
    </>
  );
}

这是我正在考虑的事情,但不会通过。

component.test.js

import Enzyme, { mount } from 'enzyme';
import EnzymeAdapter from 'enzyme-adapter-react-16';

Enzyme.configure({ adapter: new EnzymeAdapter() });

const mountSetup = (props = {}) => {
  return mount(<Component {...props} />);
};

const defaultProps = {
  isShowing: false,
  setShow: () => {},
};

describe('Component works as expected', () => {
  test('Component toggles ', () => {
    const wrapper = mountSetup(defaultProps);
    // expect(wrapper.prop('setShow')).toBeTruthy();
    wrapper.find('button').simulate('click');
    expect(wrapper.find('h1').text()).toBe("Showing")
    wrapper.unmount();
  });
});

Let's say I need to test this component. It gets the state and a setter for it through props. What should a test look like?

Component.jsx:

export function Component({ isShowing, setShow }) {
  return (
    <>
      <button
        onClick={() => {
          setShow(!isShowing);
        }}
      >
        Toggle
      </button>
      {isShowing && <h1>Showing</h1>}
    </>
  );
}

This is something I was thinking about but it doesn't pass.

Component.test.js:

import Enzyme, { mount } from 'enzyme';
import EnzymeAdapter from 'enzyme-adapter-react-16';

Enzyme.configure({ adapter: new EnzymeAdapter() });

const mountSetup = (props = {}) => {
  return mount(<Component {...props} />);
};

const defaultProps = {
  isShowing: false,
  setShow: () => {},
};

describe('Component works as expected', () => {
  test('Component toggles ', () => {
    const wrapper = mountSetup(defaultProps);
    // expect(wrapper.prop('setShow')).toBeTruthy();
    wrapper.find('button').simulate('click');
    expect(wrapper.find('h1').text()).toBe("Showing")
    wrapper.unmount();
  });
});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文