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?