React testing library: Test attribute / prop
jest-dom
toHaveAttribute
assertion asserts item
attribute while the test tries to test item
prop.
item
prop won't necessarily result in item
attribute, and since it's non-standard attribute it most probably won't.
react-testing-library
propagates functional testing and asserts resulting DOM, this requires to be aware of how components work. As can be seen here, item
props results in adding a class to grid element.
All units but tested one should be mocked in unit tests, e.g.:
...
import GridItem, { OwnProps } from "./GridItem";
jest.mock("@material-ui/core/Grid", () => ({
default: props => <div data-testid="grid-item" className={props.item && item}/>
}));
Then it could be asserted as:
expect(getByTestId("grid-item")).toHaveClass("item");
If someone is still having this issue I solved it this way:
it('Check if it is a materialUI Grid item', () => {
//Rendering the component in a constant.
const { container } = render(<YourComponent />);
//Accessing the grid wrapper. In this case by the attribute you provided.
const grid = container.querySelector('[data-testid="grid-item"]');
//What we are expecting the grid to have.
expect(grid).toHaveClass('MuiGrid-item');
})
Notes:
- I noticed that in the code item it's been declared as a string and not as a boolean: item='true', which will trigger a warning when you run the test. item={true} is the correct way of declaring it. Actually in material UI when you write item inside a grid its of course by default true, in my opinion is not necessary.
- item is a class inside material UI Grid as the previous answer correctly suggested. So by that the correct class name should be refered in this case is 'MuiGrid-item'.