I
I
IvanKalinin2016-12-27 06:09:40
React
IvanKalinin, 2016-12-27 06:09:40

How to test React components with css modules and Mocha+Enzyme?

Good time everyone.
Could you tell me how to test the components in which the class names are dynamic ( localIdentName )?
webpack.config.js

{
  loader: 'css-loader',
  options: {
    importLoaders: 1,
    modules: true,
    localIdentName: '[name]__[local]_[hash:base64:5]',
  },
},

Component Example
import React, { Component, PropTypes } from 'react';
import cn from 'classnames';

import styles from './Checkbox.scss';

export default class Checkbox extends Component {
  static propTypes = {
    onChange: PropTypes.func,
    isChecked: PropTypes.bool,
    isDisabled: PropTypes.bool,
    label: PropTypes.string,
  };

  static defaultProps = {
    onChange: () => { console.log('on change event'); }, //eslint-disable-line
  }

  handlerClick = (e) => {
    e.preventDefault();
    const { onChange, isChecked } = this.props;
    onChange(!isChecked);
  }

  render() {
    const { isChecked, isDisabled, label } = this.props;
    return (
      <label
        className={cn(
          styles.checkbox,
          {
            [styles.checked]: isChecked,
            [styles.disabled]: isDisabled,
          }
        )}
      >
        <input
          type="checkbox"
          onChange={this.handlerClick}
          disabled={isDisabled}
        />
        { label ? <span>{label}</span> : null }
      </label>
    );
  }
}

Test example:
import React from 'react';
import { expect } from 'chai';
import { shallow, mount } from 'enzyme';
import { Checkbox } from '../../app/components/Checkbox';

describe('Component: Checkbox', () => {
  it('renders component', () => {
    expect(
      shallow(
        <Checkbox />
      )
    ).to.have.length(1);
  });

  it('is checked', () => {
    const wrapper = mount(<Checkbox isChecked />);
    expect(
      wrapper
      .find('input')
      .is('[class*="checked"]')
    ).to.equal(true);
  });
});

Test result:
1) Component: Checkbox is checked:
AssertionError: expected false to equal true
+ expected - actual
-false
+true
at Context. (test/components/Checkbox.test.js:22:74)

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question