Triggering onChange function on Ant Design Slider in React Testing Library not working

Viewed 889

I made a wrapper around the Ant Design Slider. It looks like this

import React, { useState } from 'react';
import { Slider as AntSlider } from 'antd';

export function Slider(props) {
  const { value, onChangeFunction } = props;

  const [currentValue, changeValue] = useState(value);

  const onChange = (newValue) => {
    onChangeFunction();
    changeValue(newValue);
  }

  return (
    <AntSlider
      value={currentValue}
      onChange={onChange}
    />
  )

}

It's extremely simple. The only thing to note is that there is an onChange function. I am now trying to test this component with React Testing Library. Here is an example of my test

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

describe('Basic Test', () => {
  it('Should change', () => {
    const change = jest.fn();
    const wrapper = render(
      <Slider value={30} onChangeFunction={change} />
    )

    const slider = wrapper.getByRole('slider').parent;
    fireEvent.change(slider, 35);
    expect(change).toHaveBeenCalledTimes(1);
  })
})

I expect the change function to have been called, but this keeps failing. It seems like I am calling the change function in the wrong way. Is there something wrong I am doing in making this test?

Is there any way I can get the test to work? I know people say it's better to mock components, but my real components have more complicated logic in them and I'd prefer to be able to tell if the onChange function is actually getting called rather than creating a mocked component in the test file.

0 Answers
Related