0
votes

I am testing a material-UI TextField using jest and enzyme. After simulating the change event on the text field, the value is not getting updated. Am I missing something while testing in a stateless component?

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")
  })

Textfield.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;
1
where is the onChange handler implementation?Sarun UK
It's a mock function handleChange.Vrushali Bhosale

1 Answers

1
votes

I'd say that a proper way to test any material-ui component is to change its props, in this case, the value prop.

Also, as @UKS pointed out, you have mocked the onChange function, so don't be surprised that the value doesn't change.