Why Enzyme not load style from React component?

Viewed 262

I was trying to test my component style with Jest and Enzyme. I'm using TailwindCSS as my CSS framework and non ejected create-react-app. So here is my component:

import React from 'react'
import './tailwind.css' // the tailwind css

export function Alert({ children, className, icon, ...resProps }) {
  return (
    <div data-testid="qa-alert" className="my-2 p-3 text-lg bg-red-200 rounded-md flex items-center justify-center} {...resProps}>
      {icon && React.createElement(icon, { className: 'mr-2 text-xl' })}
      {children}
    </div>
  );
}

I want to test that the background color is red (bg-red-200 or #fed7d7) by using the getComputedStyle method, here is my test:

it('Should have red background color', () => {
      const wrapper = mount(<Alert />);
      const alert = wrapper.find('div');
      const style = getComputedStyle(alert.getDOMNode());
      console.log(style);

      expect(style.backgroundColor).toBe('#fed7d7');
    });

but the test fails because I don't get the background style. The received value is empty string. and the log of style is

CSSStyleDeclaration {
      '0': 'display',
      _values: { display: 'block' },
      _importants: { display: '' },
      _length: 1,
      _onChange: [Function]
    }

how can i get the style?

2 Answers

You can try to use jest-dom method toHaveStyle():

expect(alert).toHaveStyle({backgroundColor: '#fed7d7'});

You can archive it by update:

  • The selector wrapper.find('div') is too generic. Use wrapper.find('div[data-testid="qa-alert"]') or wrapper.find({'data-testid': "qa-alert"]})
  • use Enzyme hasClass to test

Example:

       it('Should have red background color', () => {
        const wrapper = mount(<Alert />);
        const alert = wrapper.find({'data-testid': "qa-alert"]});
        expect(alert.hasClass('bg-red-200')).toEqual(true);
       });
Related