Simon Legg Simon Legg - 3 months ago 32
Javascript Question

How to assert a div in a React component's data attributes using Enzyme?

I have a React component that creates a

<div>
with custom data-attributes eg



<div className="video-wrapper" data-video-source="brightcove" />


Using Enzyme I can assert the classes like so

it('creates a div with correct oVideo attributes', () => {
const videoDiv = component.find('div.video-wrapper')
expect(videoDiv.hasClass('video-wrapper')).to.equal(true);
});


But how can I assert that the
data-video-source
attribute has the value
brightcove
?

Answer

You can achieve this by using .prop() method:

it('creates a div with correct oVideo attributes', () => {
    const videoDiv = component.find('div.video-wrapper')
    expect(videoDiv.hasClass('video-wrapper')).to.equal(true);
    expect(videoDiv.prop('data-video-source')).to.equal('brightcove');
});