【问题标题】:How can I test react toggle with jest+Enzyme?如何使用 jest+Enzyme 测试反应切换?
【发布时间】:2020-07-23 09:51:10
【问题描述】:

嗨,最近我正在用 jest+enzyme 测试我的反应应用程序, 用 useState 或 useEffect 编写测试让我很困惑..

所以这是我的代码,我想测试当用户单击按钮时,描述是否显示。(通过更改状态值)

const Job = ({ job }) => {
  const [isOpen, setIsOpen] = useState(false);

  const toggle = (id) => {
    setIsOpen(!isOpen);
  };
  return (
    <Card>
    
        <Card.Text>
          <Button id="button" onClick={toggle} variant="primary">
            {!isOpen ? "View Detail" : "Hide Detail"}
          </Button>
        </Card.Text>
        {isOpen && (
          <div className="mt-4">
            <ReactMardown source={job.description} />
          </div>
        )}
    
    </Card>
  );
};

export default Job;

Job.test.js

import React from "react";

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

describe("when user click the button state value should changed", () => {
  const job = jest.fn();

  let wrapper;
  beforeEach(() => {
    wrapper = mount(<Job job={job} />);
  });
  it("should render", () => {
    expect(wrapper).not.toBeNull();
  });

  test("user click button", () => {
    const setIsOpen = jest.fn();
    wrapper.find("#button").at(1).simulate("click");
    expect(setIsOpen).toHaveBeenLastCalledWith({ isOpen: false });
  });
});

但它只通过了第一次测试..

【问题讨论】:

  • 是否应该expect(setIsOpen).toHaveBeenLastCalledWith({ isOpen: false }); 不与真比较,因为单击时值会恢复?另外我不确定 jest API,但您提供 setIsOpen 一个布尔值,但检查对象

标签: reactjs jestjs enzyme


【解决方案1】:

@nambk 我会去测试风格,例如。一些组件的background-color:

expect(component.find('#item-id').prop('style')).toHaveProperty('backgroundColor' 'black');

【讨论】:

  • header 组件中,我有const [theme, toggleTheme] = useDarkMode(); 并使用&lt;ThemeProvider theme={theme === 'light' ? lightTheme : darkTheme}&gt;。使用样式组件中的 ThemeProvider 时,状态将为“浅色”或“深色”。那么为这种情况编写测试的最佳方法是什么?
  • 在这种情况下,我建议阅读有关测试 React 钩子的内容。
【解决方案2】:

通常更好,尤其是在无状态组件中,不是测试实现,而是测试结果。

it('user click button', () => {
    expect(wrapper.find(ReactMardown)).toHaveLength(0);

    wrapper.find('#button').simulate('click');

    expect(wrapper.find(ReactMardown)).toHaveLength(1);
});

【讨论】:

  • 如何测试切换状态“亮”和“暗”的 DarkMode 按钮?
  • @nambk 我已经为你添加了答案
猜你喜欢
  • 2020-08-27
  • 2018-08-30
  • 2018-11-09
  • 1970-01-01
  • 2023-03-27
  • 2018-11-04
  • 2020-08-07
  • 1970-01-01
  • 2021-07-29
相关资源
最近更新 更多