3

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 2

0

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

expect(alert).toHaveStyle({backgroundColor: '#fed7d7'});
Sign up to request clarification or add additional context in comments.

Comments

0

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);
       });

2 Comments

I dont need the className. I need the computed style
I see. Testing of CSS is not a best practice. For better testing you should try to use testing via snapshots and visual testing

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.