React - Enzyme Test - How to check class after simulate a click

I am new in React Enzyme testing. I'd like check class name after click button, and I am getting empty class for enzyme shallow wrapper.

Button.tsx

import React from 'react';
import style from './styles.module.scss';

export interface ButtonPropTypes {
  title?: string;
}

const Button = ({ title }: ButtonPropTypes) => {
  const [active, setActive] = useState(false);

  return (
    <div
      className={cx(style.container, {
        [style.active]: active,
      })}
      onClick={() => setActive(!active)}
    >
      {title}
    </div>
  );
}

export default Button;

Button.test.tsx

import React from 'react';
import { shallow, ShallowWrapper } from 'enzyme';

import Button from './index';

let wrapper: ShallowWrapper;

beforeEach(() => {
  wrapper = shallow(<Button titie="Toggle Me"/>);
});

describe('<Button />', () => {
  it('should be defined', () => {
    expect(Button).toBeDefined();
  });

  it('should match snapshot', () => {
    expect(wrapper).toMatchSnapshot();
  });

  it('should button toggle work', () => {
    wrapper.find('div').first().simulate('click');
    console.log(wrapper.debug()); // log looks like "<div class=""> ... </div>"
    expect(wrapper.find('.active').length).toBe(0);
  });
});

Please let me know how can I check the actual wrapper class has active characters when its status is active through the toggle action.

Cheers!

1 answer

  • answered 2021-01-15 15:09 James Lin

    Make sure your project inject css classnames adding below config in jest.config.js file.

    moduleNameMapper: {
      "^.+\\.(css|less|scss)$": "identity-obj-proxy"
    }
    

    In your test file, you can check class name like below.

    ...
    
    it('should toggle action work', () =>. {
        wrapper.simulate('click');
        expect(wrapper.find('.active').length).toBe(1);
        
        wrapper.simulate('click');
        expect(wrapper.find('.active').length).toBe(0);
    });
    
    ...
    

    Good luck!