I am trying to assert that a component has a certain style in one of my tests. In the browser this component has the correct style but when I run my vitest test I get an incorrect style. It looks like default style applied to the TextField
component.
import React from "react";
import { StyledTextField } from "../src/App";
import { expect, test } from "vitest";
import { render, screen } from "@testing-library/react";
test("regular field has regular padding", () => {
render(<StyledTextField placeholder="Type some text" />);
expect(screen.getByPlaceholderText("Type some text")).toHaveStyle({
padding: "2px 12px",
});
});
import styled from "@emotion/styled";
import { TextField } from "@mui/material";
export const StyledTextField = styled(TextField)`
& .MuiOutlinedInput-root {
& .MuiOutlinedInput-input {
padding: 2px 12px;
}
}
`;
function App() {
return <StyledTextField />;
}
export default App;
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
FAIL test/App.test.tsx > regular field has regular padding
Error: expect(element).toHaveStyle()
- Expected
+ Received
- padding: 2px 12px;
+ padding: 16.5px 14px;
❯ test/App.test.tsx:9:57
7| render(<StyledTextField placeholder="Type some text" />);
8|
9| expect(screen.getByPlaceholderText("Type some text")).toHaveStyle({
| ^
10| padding: "2px 12px",
11| });
⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯
Test Files 1 failed (1)
Tests 1 failed (1)
Start at 16:02:45
Duration 1.80s (transform 66ms, setup 99ms, collect 859ms, tests 134ms, environment 420ms, prepare 72ms)
FAIL Tests failed. Watching for file changes...
press h to show help, press q to quit
Below is a codesandbox link if you would like to try it out.
Try dev 5173 to view the field and confirm that the padding: 2px 12px
.
Run the test and the padding is: padding: 16.5px 14px
Can someone help me understand whats going on here and even better provide a solution?
Thanks