Michael Lynch
Michael Lynch

Reputation: 3159

How can I write a Jest test in React to check if a component has a CSS class?

I'm using create-react-app and writing my very first test in a React component, which isn't working. I haven't installed any additional packages in my application, so I'm only using what is bundled with create-react-app by default. Here is my Button.js component:

function Button(props) {

  if(props.classes) {
    for(let i = 0; i < props.classes.length; i++) {
       btnClasses += `${props.classes[i]} `;
    }
  }

  return (
    <button className={btnClasses}>
      {props.text}
    </button>
  );
}

The component itself works. I can set the text and classes props and use it like this:

<Button text="My Button" classes={['myclass', 'myotherclass']} />

I want to write a test that checks if the button has the class when I pass one as a prop. Here is my Button.test.js:

import React from 'react';
import { render, unmountComponentAtNode } from 'react-dom';
import { act } from 'react-dom/test-utils';

import Button from './Button';

let container = null;

beforeEach(() => {
  container = document.createElement('div');
  document.body.appendChild(container);
});

describe('Button', () => {

  it('renders with classes', () => {
    act(() => {
      render(<Button classes={['myclass']} />, container);
    });
    expect(container.classList.contains('myclass')).toBe(true);
  });
});

This test fails and I don't know why. I was under the impression that you can interact with container like any other DOM node. When I console.log(container.classList), I get an empty DOMTokenList {}. What am I missing? Why doesn't this test work?

Upvotes: 1

Views: 4650

Answers (2)

lakewood
lakewood

Reputation: 607

The beforeEach(); setup is setting up a div, which is wrapping around your component. Target the element inside of your container.

describe('Button', () => {

  it('renders with classes', () => {
    act(() => {
       render(<Button classes={['myclass']} />, container);
   });

  expect(container.querySelector('button').classList.contains('myclass')).toBe(true);
});

Upvotes: 1

Roman Unt
Roman Unt

Reputation: 893

You need to use enzyme https://airbnb.io/enzyme/ for testing your React components. Jest is just for testing functionality and logic as well.

This example will help you: https://airbnb.io/enzyme/docs/api/ReactWrapper/hasClass.html

Upvotes: 0

Related Questions