I want to test to see whether an image has properly loaded in a React app. I have decided to check the src
attribute of the img
element nested within the React component. I want to use the Jest testing framework and, if needed, the Enzyme testing utility.
By digging through the Object.keys
of a shallow React test component, I was able to come up with the following solution. The line I'm uncertain about is indicated with the asterisks.
import React from 'react';
import {shallow} from 'enzyme';
import App from './App';
it('should have the logo image', () => {
const app = shallow(<App />);
const img = app.find('img');
const src = img.node.props.src; // ******
expect(src).toBe('logo.svg');
});
This solution does work but it seems a little convoluted (it requires a property of a property of a property of a wrapper) and seems somewhat obscure (I can't easily find clear instructions for this online). So, is this the correct/simplest way to do this?
getAttribute
or retrieveProp
method, etc. in Enzyme? Is there a better way of doing this using something else instead of Enzyme, e.g. react-addons-test-utils
?This question about React element attributes doesn't seem to quite answer it for me even though the poster there also indicates having a hard time finding documentation about asserting a rendered attribute value. A number of other questions (e.g. here, here and here) deal with React/Jest/Enzyme but don't deal with retrieving attribute values.
After some digging, I found the following. The indicated line in the question:
const src = img.node.props.src;
can be simplified to the following:
const src = img.prop('src');
The documentation can be found here.
If someone knows of a non-Enzyme way of doing this, I'd still be interested in hearing about it.