react-testing-library icon indicating copy to clipboard operation
react-testing-library copied to clipboard

Onchange event not being fired when using fireEvent.change

Open jamesBennett opened this issue 7 years ago • 21 comments

When trying to use fireEvent.change on an input The onChange event isn't triggered. I am seeing the onBlur event is triggered for fireEvent.blur

  • "jest": "24.9.0",
  • "jest-environment-jsdom-fourteen": "^0.1.0",
  • "jest-localstorage-mock": "2.4.0",
  • "jest-serializer-enzyme": "1.0.0",
  • "jest-skipped-reporter": "0.0.4",
  • "jest-trx-results-processor": "0.2.0",
  • "jest-watch-typeahead": "0.3.0",
  • "@testing-library/react": "^9.3.0",
  • "react-hooks-testing-library": "0.4.0",
  • "ts-jest": "24.1.0",
  • "react": "16.9",
  • "react-dom": "16.9",
  • node version: v8.16.1
  • yarn "1.17.3"

What you did:

when I use fireEvent.change(input, {target: {value: 'bob'}} OnChange isn't triggered When I use fireEvent.blur(input) Blur is triggered When I use simulate for react-dom/test-utils it works.

Things I've tried

using "jest-environment-jsdom-fourteen": "^0.1.0", checking to make sure input fields have type set.

example test

it.only('should map errors', async () => {
        const { container, getByLabelText, getByText } = await renderWithState();
        const routingNumber = getByLabelText('Routing number') as HTMLInputElement;
        const accountNumber = getByLabelText('Account number') as HTMLInputElement;
        const accountConfirm = getByLabelText('Confirm account number') as HTMLInputElement;
        fireEvent.change(routingNumber, { target: { value: '110000000', name: EBankingFieldNames.routingNumber } });
        fireEvent.change(accountNumber, { target: { value: '000444444440', name: EBankingFieldNames.accountNumber } });
        fireEvent.change(accountConfirm, {
            target: { value: '000444444440', name: EBankingFieldNames.accountNumberConfirm },
        });
        await waitForDomChange({ container });
        fireEvent.click(getByText('Save'));
        await waitForDomChange({ container });
        expect(getByText('Please enter a valid routing number'));
    });

jamesBennett avatar Nov 15 '19 19:11 jamesBennett

Hi @jamesBennett,

I'm not sure whether it will make a difference, but I noticed that you're not adding await on your waitForDomChange calls there. Those are async so you'll need to await those.

kentcdodds avatar Nov 15 '19 20:11 kentcdodds

We could help a lot more if you post a codesandbox reproduction of this.

kentcdodds avatar Nov 15 '19 20:11 kentcdodds

Hi @jamesBennett,

I'm not sure whether it will make a difference, but I noticed that you're not adding await on your waitForDomChange calls there. Those are async so you'll need to await those.

Yeah doesn't change anything. Even if I had the await the onChange should be called before hitting the waitForDomChange

jamesBennett avatar Nov 15 '19 20:11 jamesBennett

We could help a lot more if you post a codesandbox reproduction of this.

My app is really large. That seems like it would take a significant amount of time. Also, I have enzyme in here as well. Could that be anything?

jamesBennett avatar Nov 15 '19 20:11 jamesBennett

I doubt that enzyme is causing a problem. Without a reproduction of the problem it's impossible for us to help because this works for everyone else.

kentcdodds avatar Nov 15 '19 21:11 kentcdodds

@kentcdodds So the problem is that if you don't set the type or the type is invalid for an input it will not trigger an onChange.

Although this is definitely my error it seems odd that onBlur would still work. Is this a known bug? Seems like the query functions should throw an error on this.

jamesBennett avatar Nov 15 '19 22:11 jamesBennett

if you don't set the type or the type is invalid for an input it will not trigger an onChange.

I think there's something else about your set up because this test passes:

import React from 'react'
import {render, fireEvent} from '@testing-library/react'

test('calls change handler for an input', () => {
  const handleChange = jest.fn()
  const {container} = render(<input onChange={handleChange} />)
  const input = container.firstChild
  fireEvent.change(input, {target: {value: 'a'}})
  expect(handleChange).toHaveBeenCalledTimes(1)
})

https://codesandbox.io/s/rtl-calls-change-handler-dh3gs?fontsize=14&hidenavigation=1&module=%2Fsrc%2F__tests__%2Findex.js&previewwindow=tests&theme=dark

This is why having a reproduction is a great deal of help.

kentcdodds avatar Nov 15 '19 23:11 kentcdodds

I think there's something else about your set up because this test passes:

But this version fails.

import React from 'react'
import {render, fireEvent} from '@testing-library/react'

test('calls change handler for an input', () => {
  const handleChange = jest.fn()
  const {container} = render(
    <input onChange={handleChange} type="invalidType" />,
  )
  const input = container.firstChild
  fireEvent.change(input, {target: {value: 'a'}})
  expect(handleChange).toHaveBeenCalledTimes(1)
})

jamesBennett avatar Nov 16 '19 00:11 jamesBennett

notice the type

jamesBennett avatar Nov 16 '19 00:11 jamesBennett

Yeah, that's a bug. I'm not sure what the problem is here and it will need some investigation. I wonder whether it's a limitation for jsdom.

Anyone's invited to do some investigation as to why an onChange handler is working when rendering it to the app, but not in the test. Here's a codesandbox example of this issue:

https://codesandbox.io/s/rtl-change-handler-with-invalid-type-yipu3

kentcdodds avatar Nov 16 '19 05:11 kentcdodds

it's a limitation for jsdom.

@kentcdodds I don't think so because it works fine with reacts simulate.change https://codesandbox.io/s/rtl-calls-change-handler-pfnks?fontsize=14&hidenavigation=1&theme=dark

jamesBennett avatar Nov 16 '19 06:11 jamesBennett

Simulate doesn't fire events. Simulate is cheating, which is why we don't use it.

kentcdodds avatar Nov 16 '19 14:11 kentcdodds

I did some digging into this and it looks like the root cause is JSDOM not defaulting invalid input types to "text" as per the spec:

The missing value default and the invalid value default are the Text state.

I tracked it down to React only creating change events when the input has a valid type: https://github.com/facebook/react/blob/ab1a4f249e61045d523ddbbfb840e868afbbf785/packages/react-dom/src/events/ChangeEventPlugin.js#L275 https://github.com/facebook/react/blob/ab1a4f249e61045d523ddbbfb840e868afbbf785/packages/shared/isTextInputElement.js#L13-L29

I've opened a PR with JSDOM that should address the issue, however I think Jest is using JSDOM 14 so it might be some time for this change to filter through the right packages.

connormeredith avatar Nov 17 '19 09:11 connormeredith

Super! Thank you for doing that! Glad to get this taken care of 👍

kentcdodds avatar Nov 17 '19 14:11 kentcdodds

Doesn't seem to be only for invalid types. The following doesnt work:

test('calls change handler for an input', () => {
    const handleChange = jest.fn()
    const { container } = render(<input type="radio" onChange={handleChange} />)
    const input = container.firstChild
    fireEvent.change(input, { target: { value: 'a' } })
    expect(handleChange).toHaveBeenCalledTimes(1)
})

RobertSigma avatar May 19 '20 11:05 RobertSigma

@RobertSigma, you can't change the value of a radio button to "a"... that doesn't make sense. For radio and checkboxes you "click" them.

kentcdodds avatar May 19 '20 17:05 kentcdodds

@RobertSigma, you can't change the value of a radio button to "a"... that doesn't make sense. For radio and checkboxes you "click" them.

I'm starting to think we should add some warnings to fireEvent.change in dom-testing-library. It feels like we get a lot of reports that come down to wrong usage of fireEvent.change with certain input types (e.g. type="date" and non iso values).

eps1lon avatar May 19 '20 18:05 eps1lon

Ive had the same issue using function callback in setState. With object literal it works:

  // This doesnt work:
  this.setState((state) => ({
     value: e.target.value
  }));
  
  // This does:
  this.setState({value: e.target.value});

crtl avatar May 21 '21 14:05 crtl

Hi @kentcdodds

Depending on this answer

If we have a custom date picker of 3 inputs wrapped with a container (div), how can we pass type or make fireEvent.change work?

    <Row data-testid={testId} gutter={[16, 16]}>
      <Col xs={8}>
        <InputField
          ariaLabel="day"
          disabled={disabled}
          error={error}
          maxLength={2}
          onChange={(event) => handleOnChange(event.target.value, 'day')}
          placeholder={t('datePicker.day')}
          ref={dayRef}
          size={size}
          testId={`${testId}-day`}
          type="number"
        />
      </Col>

      <Col xs={8}>
        <InputField
          ariaLabel="month"
          disabled={disabled}
          error={error}
          maxLength={2}
          onChange={(event) => handleOnChange(event.target.value, 'month')}
          placeholder={t('datePicker.month')}
          ref={monthRef}
          size={size}
          testId={`${testId}-month`}
          type="number"
        />
      </Col>

      <Col xs={8}>
        <InputField
          ariaLabel="year"
          disabled={disabled}
          error={error}
          maxLength={4}
          min={1900}
          onChange={(event) => handleOnChange(event.target.value, 'year')}
          placeholder={t('datePicker.year')}
          ref={yearRef}
          size={size}
          testId={`${testId}-year`}
          type="number"
        />
      </Col>
    </Row>

This is my custom implementation

DatePicker.tsx

import {Col, Input, Row} from 'antd';
import {SizeType} from 'antd/es/config-provider/SizeContext';

import React, {useCallback, useEffect, useRef, useState} from 'react';

import {useTranslation} from 'react-i18next';
import {InputField} from '../InputField';

const padWithZero = (value: number) =>
  (value < 10 ? `0${value}` : value) as string;

const checkMaxYears = (value: number) => {
  if (!value) return '';
  return (value > 9999 ? `9999` : value) as string;
};

const checkMaxDay = (value?: number) => {
  if (!value) return '';
  return (value > 31 ? '31' : value) as string;
};

const checkMaxMonth = (value?: number) => {
  if (!value) return '';
  return (value > 12 ? '12' : value) as string;
};

interface DatePickerProps {
  prefixIcon?: React.ReactNode;
  placeholder?: string;
  size?: SizeType;
  value?: string;
  disabled?: boolean;
  onChange?: (date: string | null) => void;
  testId?: string;
  error?: boolean;
}

const DatePickerField: React.FC<DatePickerProps> = ({
  onChange,
  disabled,
  testId,
  size,
  error,
  value,
}) => {
  const dayRef = useRef<Input | null>(null);
  const monthRef = useRef<Input | null>(null);
  const yearRef = useRef<Input | null>(null);

  const {t} = useTranslation();

  const handleOnChange = useCallback(
    (selectedValue: string | number, fieldType: 'day' | 'month' | 'year') => {
      const dayValue = dayRef.current?.state.value;
      const monthValue = monthRef.current?.state.value;
      const yearValue = yearRef.current?.state.value;

      let dateFormat = [];

      if (fieldType === 'day') {
        const validValue = checkMaxDay(+selectedValue);
        dateFormat = [padWithZero(+validValue), monthValue, yearValue];
      } else if (fieldType === 'month') {
        const validValue = checkMaxMonth(+selectedValue);
        dateFormat = [dayValue, padWithZero(+validValue), yearValue];
      } else {
        dateFormat = [dayValue, monthValue, checkMaxYears(+selectedValue)];
      }

      dayRef.current?.setValue(dateFormat[0]);
      monthRef.current?.setValue(dateFormat[1]);
      yearRef.current?.setValue(dateFormat[2]);
      if (dateFormat[0] && dateFormat[1] && dateFormat[2]) {
        onChange?.(dateFormat.join('-'));
      }
    },
    [onChange]
  );

  useEffect(() => {
    if (value) {
      const [day, month, year] = value?.split('-');

      dayRef.current?.setValue(day);
      monthRef.current?.setValue(month);
      yearRef.current?.setValue(year);
    }
  }, [value]);

  return (
    <Row data-testid={testId} gutter={[16, 16]}>
      <Col xs={8}>
        <InputField
          ariaLabel="day"
          disabled={disabled}
          error={error}
          maxLength={2}
          onChange={(event) => handleOnChange(event.target.value, 'day')}
          placeholder={t('datePicker.day')}
          ref={dayRef}
          size={size}
          testId={`${testId}-day`}
          type="number"
        />
      </Col>

      <Col xs={8}>
        <InputField
          ariaLabel="month"
          disabled={disabled}
          error={error}
          maxLength={2}
          onChange={(event) => handleOnChange(event.target.value, 'month')}
          placeholder={t('datePicker.month')}
          ref={monthRef}
          size={size}
          testId={`${testId}-month`}
          type="number"
        />
      </Col>

      <Col xs={8}>
        <InputField
          ariaLabel="year"
          disabled={disabled}
          error={error}
          maxLength={4}
          min={1900}
          onChange={(event) => handleOnChange(event.target.value, 'year')}
          placeholder={t('datePicker.year')}
          ref={yearRef}
          size={size}
          testId={`${testId}-year`}
          type="number"
        />
      </Col>
    </Row>
  );
};

export default DatePickerField;

Calling DatePickerField component.

                <DatePickerField
                  disabled={disableBasicInformation}
                  error={!!birthdateError}
                  onChange={(date: string | null) => {
                    console.log('Never called with fireEvent.change', date);
                    // onChange(date);
                  }}
                  placeholder={t('orderInformation.dateOfBirthPlaceholder')}
                  size="large"
                  testId="birthdate-input"
                  // value={value}
                />

I'm just stuck and confused because this implementation works perfectly on run-time!! Any idea?

AhmedBHameed avatar Jul 26 '21 09:07 AhmedBHameed

This is killing me

wi-ski avatar Jan 05 '22 05:01 wi-ski