useEffect trigger when a prop changes cannot be tested

297 views Asked by At

I'm trying to test a react component using jest and enzyme. There is a useEffect trigger when a prop changes and I am unable to test it properly. The assertion fails due to undefined value.

This is my simplified component

export function SongDataModal(props) {
    const [name, setName] = useState('');

    useEffect(() => {
        if (props.songData.songName ?? false) {
            setName(props.songData.songName);
        }
    }, [props.songData.songName]);

    return (
        <Input
            type="search"
            id="song-name-input"
            disabled={true}
            value={name}
        />
    );
}

SongDataModal.propTypes = {
    songData: PropTypes.object,
};
const mapStateToProps = (state) => ({
    songData: state.songDataReducer
});

const mapDispatchToProps = (dispatch) => bindActionCreators({
//removed the actions since they are not related
}, dispatch);

export default connect(mapStateToProps, mapDispatchToProps)(SongDataModal);


And this is my test file

describe('SongDataModal', () => {
  let wrapper;
  const songData = { songName: 'Avicii - Levels' };

  beforeEach(() => {
    wrapper = shallow(
      <SongDataModal
       songData={songData}
      />
    );
  });

  it('shows the song name on initial loading', () => {
    expect(wrapper.find('#song-name-input').prop('value')).toBe('Avicii - Levels');
  });
});
1

There are 1 answers

1
Urvashi Sharma On

You can use the act() method from RTL. I generally use it to test any conditional function calls that may happen from inside a useEffect hook. I use the render method for my purpose like this:

await act(() =>render(<Component/>))

After this, you could use async-await to waitFor the value to change or for a function inside the useEffect hook to be called. Hope that helps. Additionaly, you could check this out for more insight.