首页 > 解决方案 > jest +酵素:不更新材料输入值

问题描述

我正在使用 jest 和酶测试材料 UI 文本字段。在文本字段上模拟更改事件后,值没有得到更新。在无状态组件中测试时我是否遗漏了什么?

textfield.spec.js

it("on input change should call onChange function passed through props",()=>{
    const handleChange = jest.fn();
    let props = {
        label: 'Test Label',
        type: 'text',
        name: 'email',
        value: "Hello World",
        index: 0,
        input: {},
        defaultValue:'default',
        meta: {
            touched: true,
            error: 'error'
        },
        onChange:handleChange,
    }
    const wrapper = mount(<Textfield {...props}/>);
    wrapper.find('input').simulate('change',{target:{name:'email',value:"hello"}});
    wrapper.update();
    expect(handleChange).toHaveBeenCalled();     
    expect(wrapper.find('input').prop('value')).toBe("hello")
  })

文本字段.js

import React from 'react';
import TextField from '@material-ui/core/TextField';
import './style.scss';
const Textfield = (props) => {
  const {label,value,onChange,className,name,id,onKeyDown,multiline,index,error,inputProps,errorMsg,isDisabled} = props;
  return (
    <TextField
      error={error}
      id={id}
      label={error ? "Incorrect Field" : label}
      variant="filled"
      value={value}
      onChange={onChange}
      classname={className}
      name={name}
      onKeyDown={onKeyDown}
      multiline={multiline}
      helperText={error && "Incorrect Field."}
      inputProps={{
        ...inputProps,
        'data-testid': id
      }}
      disabled={isDisabled}
    />
  );
};

export default Textfield;

标签: reactjsunit-testingjestjsenzyme

解决方案


我想说测试任何material-ui组件的正确方法是更改​​其道具,在本例中为value道具。

此外,正如@UKS 指出的那样,您已经模拟了该onChange函数,所以不要对值没有改变感到惊讶。


推荐阅读