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.
Snapshot testing is a very useful technique to test React component snapshots using the Jest library.
Jest can be used without Enzyme to render components and test with snapshots, Enzyme simply adds additional functionality. Enzyme can be used without Jest, however Enzyme must be paired with another test runner if Jest is not used.
Introduction. An attribute is a property of an element used to provide access to additional data required for that specific element to process the output.
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.
For me, it worked as below
expect(companySelect.find('input').props()["disabled"]).toBe(true)
props()
returns an object having all the attributes of the selector and then it can be browsed as an object.
Hope this helps too....
https://airbnb.io/enzyme/docs/api/ReactWrapper/props.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With