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');
});
});
You can use the
act()method from RTL. I generally use it to test any conditional function calls that may happen from inside auseEffecthook. I use therendermethod for my purpose like this:After this, you could use async-await to
waitForthe value to change or for a function inside theuseEffecthook to be called. Hope that helps. Additionaly, you could check this out for more insight.