Фермент имитирует изменение ввода, которое не работает

#javascript #reactjs #typescript #enzyme

#javascript #reactjs #typescript #enzyme

Вопрос:

У меня есть компонент ввода React, подобный этому.

 const Input: InputComponent = props => {
  const { limit, suffix, className, onChange } = props;
  const [inputLength, setInputLength] = useState(0);
  const inputRef = useRef<HTMLInputElement>();

  const handleChange = (val: string, e: any): void => {
    setInputLength(val.length);
    onChange?.(val, e);
  };

  useEffect(() => {
    limit amp;amp; setInputLength((inputRef?.current as any)?.state?.value?.length || 0);
  }, []);

  const { prefixCls: common } = useConfigContext();
  const prefixCls = `${common}-input`;

  return (
    <Component
      {...props}
      className={cx(className, prefixCls)}
      onChange={handleChange}
      ref={inputRef as any}
      suffix={
        limit ? (
          <div className={cx(`${prefixCls}__limit`)}>
            {inputLength}/{limit}
          </div>
        ) : (
          suffix
        )
      }
    />
  );
};
  

в моем Input.spec.tsx

   it('onChange listener correctly', () => {
    const onChange = jest.fn();
    const component = mount(<Input onChange={onChange} defaultValue={'default'} />);
    const input = component.find('input');
    input.simulate('change', {
      target: {
        value: 'test',
      },
    });
    console.log(input.props()); // input value still show `default`
    expect(onChange.mock.calls.length).toBe(1);
  });
  

Входное значение по-прежнему показывает значение по умолчанию (‘default’), не меняясь на ‘test’.
Однако вызывается событие onChange.

Кто-нибудь может дать мне некоторые рекомендации, где я ошибся?

Ответ №1:

Попробуйте следующий подход (просто предположение)

  it('onChange listener correctly', () => {
    const onChange = jest.fn();
    const component = mount(<Input onChange={onChange} defaultValue={'default'} />);
    const input = component.find('input');
    input.simulate('change', {
      target: {
        value: 'test',
      },
    });
    component.update();
    console.log(input.props()); // input value still show `default`
    expect(onChange.mock.calls.length).toBe(1);
  });
  

обновление () — https://enzymejs.github.io/enzyme/docs/api/ShallowWrapper/update.html

Комментарии:

1. привет, спасибо, но в моем случае это не работает. реквизиты по-прежнему отображаются по умолчанию. Есть ли у вас какие-либо другие предположения о том, почему это происходит? Спасибо