【问题标题】:How to test onChange for ui-material TextField using Jest and Enzyme如何使用 Jest 和 Enzyme 测试 ui-material TextField 的 onChange
【发布时间】:2026-02-13 16:00:01
【问题描述】:

我是测试新手,我不知道如何测试 TextField 组件中的变化值

   export const ParentComponent = ({
    question,
    onValueChange
    }: ParentProps) => {

    const [value, setValue] = useState(default);

    const onChange = event => {
    const answer = event.target.value;
    setValue(answer);
    clearTimeout(timeout);
    timeout = setTimeout(() => {
      onValueChange(question);
     }, 500);
    };

return (
    <TextField
      className={classes.textField}
      InputLabelProps={{
        className: classes.color
      }}
      onChange={onChange}
      value={value || ""}
    />);
   };

这是我到目前为止阅读的其他答案的内容,不确定如何处理 onValueChange 和 onChange 之间的区别:

describe("ParentComponent", () => {
  let mount;
   
  beforeEach(() => {
    mount = createMount();
  });
  afterEach(() => {
    mount.cleanUp();
  });
  it("renders", () => {
    const wrapper = mount(<ParentComponent question={Question} onValueChange={() => {}} />);
    expect(wrapper).not.toBeNull();
  });



 it("Should change value when text is entered", () => {
        const onChange = jest.fn();
        const wrapper = mount(<ParentComponent question={Question} onValueChange={() => {}} />);
        const event = {
          target: {
            value: "This is just for test"
          }
        };
        wrapper.find(TextField).simulate("change", event);
        expect(onChange).toHaveBeenCalled();
        expect(onChange).toHaveBeenCalledWith("This is just for test");
      });

收到此错误:

Error: expect(jest.fn()).toHaveBeenCalled()
Expected number of calls: >= 1
Received number of calls:    0

【问题讨论】:

    标签: reactjs unit-testing jestjs material-ui enzyme


    【解决方案1】:

    首先,您必须监视onChange 函数:

    const onChange = jest.spyOn(TextField.prototype, 'onChange');
    

    @material-ui 提供了复杂的组件,所以我猜你会这样测试它(还要注意酶的find() 返回一个节点集合):

    wrapper.find(TextField).find('input').at(0).simulate('change', event);
    

    【讨论】:

    • “首先,你必须监视 onChange 函数”是什么意思。你能用更多的代码解释一下吗?
    • 当然,感谢您的编辑...关于解释,我想说酶的spy 是它非常基本的概念,既然您已经正确编辑了我的答案,我猜您已经了解基本原理...请提出一些更具体的问题。
    • 对我来说这个解决方案不起作用。所以我使用了jest.spyOn(wrapper.find(TextField).props(), 'onChange'),它成功了。