4
votes

I'm trying to test a state change via React Hooks (useState) by simulating a changed value on a Material UI slider, since that calls my hooks state update function. I'm then trying to verify the change by checking text that's displayed on the page. I feel like I've gotten close, no syntax errors yelling at me anymore, but it seems like the change isn't happening.

I've tried multiple different selectors and found that most people online are importing their Material UI element and using the imported item as the selector. I've tried this with and without .as(0), with a value of 500 as both a string and a number, and other variations.

My slider's onChange method directly calls my hooks state update method with the e.target.value to set as the new state value (and that all works fine in the actual app).

Any ideas of other things I can try? Or maybe there's another better way to test state changing with React hooks?

import ReactDOM from 'react-dom';
import App from './App';
import { createMount } from '@material-ui/core/test-utils';
import Slider from "@material-ui/core/Slider";

describe('App', () => {
  let mount;

  beforeEach(() => {
    mount = createMount();
  });

  afterEach(() => {
    mount.cleanUp();
  });


  it('updates the volts displayed when the slider value changes', () => {
    const wrapper = mount(<App />);
    wrapper.find(Slider).at(0).simulate('change', { target: { value: 500 } });
    expect(wrapper.find('.volts-screen').text()).toEqual('0.500');
  })

}```



ERROR


expect(received).toEqual(expected) // deep equality

    Expected: "0.500"
    Received: "0.000"
1
please add the code of your component.Fabian Hinsenkamp
Thanks for your message. I ended up figuring it out and will edit my post in case others are looking for the answer to the same thing.Lynne Rang

1 Answers

4
votes

Ended up figuring it out. I imported the slider from material core (in the same way as in my component), and then I used the imported element in my wrapper.find and simulated a change with a second argument of { target: { value: 500 }}.

I thought this wasn't working at first, but realized that because in my case the effect was updating my component state which is async, I needed to add a setTimeout to make sure the update was captured before my check ran.

Saw some similar guidance on other Material UI elements, but didn't realize the slider would be so similar. Will leave this here just in case some other poor soul is scouring the internet for "Slider"-related info in particular ;)

//imported the element as below
import Slider from "@material-ui/core/Slider";

// found in wrapper using that element and simulated change with target value on timeout
it('updates the volts displayed when the slider value changes', () => {
    const wrapper = mount(<App />);
    wrapper.find(Slider).at(0).simulate('change', { target: { value: 500 } });
    setTimeout(() => expect(wrapper.find('.volts-screen').text()).toEqual('0.500'), 0);
  })