6
votes

When testing a react component which uses className to set the css class using enzyme (mount or shallow) I'm able to test correctly when it's a div but unable to get it to work on an h1 tag.

Is this some

  • thing to do with mount or shallow?
  • Is it something I'm missing?
  • Is it a bug?

Any thoughts appreciated!

JSX:

import React from 'react'

export const PageNotFound = ({heading, content, wrapperCSS, headingCSS, contentCSS}) => (
<div className={ wrapperCSS }>
  <div className={ contentCSS }>
    { content }
  </div>
  <h1 className={ headingCSS }>{ heading }</h1>
</div>
)

PageNotFound.propTypes = {
    heading: React.PropTypes.string,
    content: React.PropTypes.string,
    wrapperCSS: React.PropTypes.string,
    headingCSS: React.PropTypes.string,
    contentCSS: React.PropTypes.string
};

PageNotFound.defaultProps = {
    heading: '404',
    content: 'Page Not Found',
    wrapperCSS: 'wrapper',
    headingCSS: 'heading',
    contentCSS: 'content'
};

export default PageNotFound

Spec:

import React from 'react'
import { expect } from 'chai'
import { shallow, mount } from 'enzyme'

import PageNotFound from './PageNotFound'

describe('<PageNotFound/>', function() {

let wrapper;

beforeEach(() => {
    wrapper = mount(<PageNotFound contentCSS="mycontent" headingCSS="myheader" content="Message" heading="My Title" />);
})

it('Uses heading prop', () => {
    expect(wrapper.find('h1').text()).to.eq('My Title')
});

it('Uses headingCSS prop', () => {
    console.log(wrapper.html());
    expect(wrapper.find('h1.myheader').length).to.eq(1)
});

it('Uses content prop', () => {
    expect(wrapper.find('div.mycontent').text()).to.eq('Message')
});


});

Test Results:

Notice the debug log which shows the h1 with class myheader, but the test fails with zero elements found for h1.myheader

<PageNotFound/>
    ✓ Uses heading prop
LOG LOG: '<div class="_2t--u"><h1 class="myheader">My Title</h1><div class="mycontent">Message</div></div>'
    ✗ Uses headingCSS prop
    expected 0 to equal 1
    [email protected]:11:24087
    [email protected]:14:52974
    [email protected]:14:55858
    tests.webpack.js:15:17123
    tests.webpack.js:14:10442

    ✓ Uses content prop
2

2 Answers

5
votes

Weird. It should work.

Anyway, you could try taking advantage of Enzyme's API instead.

For this particular test, .hasClass() should do the job and is clearer about its intent:

expect(wrapper.find('h1').hasClass('myheader')).to.eq(true)
2
votes

The problem here is that your import import styles from './styles.module.css' is not actually being loaded.

It is likely that you have something in a test setup file to mock out anything with a css extension:

require.extensions['.css'] = function () {
  return null;
};

I don't have enough rep, or I would have just commented this. Unfortunately, I don't yet know a way to actually import these styles, as you can tell from my question here: WebPack LESS imports when testing with Mocha