I tried to test if my hover work or not , here's my code to be tested
//styled components + typescript
const Info = styled.div`
opacity: 0;
width:100%;
height: 100%;
position: absolute;
top:0;
left:0;
background-color: rgba(0,0,0,0.2);
z-index:3;
display: flex;
align-items: center;
justify-content: center;
transition: all 0.5s ease;
cursor: pointer;
`
const Container = styled.div`
flex:1;
margin:5px;
min-width:280px;
height:350px;
display: flex;
align-items: center;
justify-content: center;
background-color: #f5fbfd;
position: relative;
&:hover ${Info}{
opacity: 1;
}
`
const ProductItem = ({item}:ProductItemProp) => {
return (
<Container data-testid="productContainer">
<Circle/>
<Image src={item.img}/>
<Info data-testid="productInfo">
<Icon data-testid="productIcon">
<ShoppingCartOutlined/>
</Icon>
<Icon>
<SearchOutlined/>
</Icon>
<Icon>
<FavoriteBorderOutlined/>
</Icon>
</Info>
</Container>
)
}
export default ProductItem
I want to test if opacity become 1 when I hover the elements
Product.test.tsx
import userEvent from '@testing-library/user-event'
import "@testing-library/jest-dom/extend-expect";
import ProductItem from "./ProductItem";
test("Check Product Hover", () => {
const { getByTestId } = render(
<ProductItem item={{ id: 7, img: "https://i.imgur.com/aYMvzlX.png" }} />
);
const productContainer = getByTestId("productContainer");
const productInfo = getByTestId("productInfo");
userEvent.hover(productContainer)
expect(productInfo).toHaveStyle("opacity:1");
});
But the test results still show 0 , so I don't know wha't going on , I know this test is a little bit unnecessary , but I am new to this library and I want to try everything out.
- Expected
- opacity: 1;
+ opacity: 0;
It would be helpful if you provided a reproducible example of your setup in a codesanbox or similar, but you might want to add styled-component's jest integration tools.
Docs - https://styled-components.com/docs/tooling#jest-integration
More docs - https://github.com/styled-components/jest-styled-components/blob/main/README.md
Not sure if that's the problem, but you can give it a try.
Ex.:
import userEvent from '@testing-library/user-event'
import "@testing-library/jest-dom/extend-expect";
import ProductItem from "./ProductItem";
import 'jest-styled-components'
test("Check Product Hover", () => {
const { getByTestId } = render(
<ProductItem item={{ id: 7, img: "https://i.imgur.com/aYMvzlX.png" }} />
);
const productContainer = getByTestId("productContainer");
const productInfo = getByTestId("productInfo");
userEvent.hover(productContainer)
// expect(productInfo).toHaveStyle("opacity:1");
// Use this instead - toHaveStyleRule is a custom matcher from jest-styled-components
expect(productInfo).toHaveStyleRule("opacity", "1");
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With