Improving the clarity of Jest snapshot test logs using styled from MUI

Currently, I am working with MUI v5 along with styled components and Jest snapshot testing. I am looking for a way to improve the logs generated when a snapshot test fails.

Below is an example of the component I am dealing with:

const styledProperties = new Set(['backgroundColor']);

const StyledAppBar = styled(AppBar, {
    shouldForwardProp: (property) => !styledProperties.has(property.toString())
})<IHeaderProperties>(({ backgroundColor, theme }) => ({
    backgroundColor: backgroundColor || theme.palette.background.paper
}));

export interface IHeaderProperties extends ICommonProperties {
    backgroundColor?: string;
}

export default function Header(properties: PropsWithChildren<IHeaderProperties>): ReactElement {
    return <StyledAppBar {...properties} />;
}

This is how a snapshot test looks like:

describe('given <Header />', () => {
  describe('when it is rendered', () => {
      it('should match snapshot', () => {
          renderWithProviders(<Header data-testid="Header" backgroundColor={'#FFFFFF'} />);

          const header = screen.getByTestId('Header');

          expect(header).toBeVisible();
          expect(header).toMatchSnapshot();
      });
  });
});

When the snapshot fails, only the part related to "css-PART_THAT_CHANGES-MuiPaper-root-MuiAppBar-root" is displayed.

    expect(received).toMatchSnapshot()

    Snapshot name: `given <Header /> when it is rendered should match snapshot 1`

      -
      Snapshot - 1 +
      Received + 1

      <
      header -
      class = "... css-1adzlm4-MuiPaper-root-MuiAppBar-root" +
      class = "... css-11m65ae-MuiPaper-root-MuiAppBar-root"
    data - testid = "Header" /
      >

I would prefer to have something similar to this design:

https://i.sstatic.net/PHLTF.png

Answer №1

I made the decision to utilize the resources available at https://github.com/emotion-js/emotion/tree/main/packages/jest. So far, it's performing quite well. Here is a sample of my snapshots:

exports[`given <IconButton /> when ... should match snapshot 1`] = `
.emotion-0 {
  display: -webkit-inline-box;
  display: -webkit-inline-flex;
  display: -ms-inline-flexbox;
  display: inline-flex;
  -webkit-align-items: center;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  -webkit-justify-content: center;
  justify-content: center;
  position: relative;
  box-sizing: border-box;
  -webkit-tap-highlight-color: transparent;
  background-color: transparent;
  outline: 0;
  border: 0;
  margin: 0;
  border-radius: 0;
  padding: 0;
  cursor: pointer;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  vertical-align: middle;
  -moz-appearance: none;
  -webkit-appearance: none;
  -webkit-text-decoration: none;
  text-decoration: none;
  color: inherit;
  text-align: center;
  -webkit-flex: 0 0 auto;
  -ms-flex: 0 0 auto;
  flex: 0 0 auto;
  font-size: 1.5rem;
  padding: 8px;
  border-radius: 50%;
  overflow: visible;
  color: #fff;
  -webkit-transition: background-color 150ms cubic-bezier(0.4, 0, 0.2, 1) 0ms;
  transition: background-color 150ms cubic-bezier(0.4, 0, 0.2, 1) 0ms;

  // Additional styles and classes

<button
  class="MuiButtonBase-root MuiIconButton-root MuiIconButton-sizeMedium emotion-0"
  data-testid="IconButton"
  tabindex="0"
  type="button"
>
  <span
    class="MuiTouchRipple-root emotion-1"
  />
</button>
`;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error in Angular SSR: Build failed due to project reference without "composite" setting set to true

Currently facing an issue while developing an Angular App with SSR. When using npm run build:ssr, the following errors are displayed: ERROR in [...]/tsconfig.json [tsl] ERROR TS6306: Referenced project '[...]/tsconfig.app.json' must have se ...

What is the best way to fetch all Firebase database IDs using Angular?

Is there a way to fetch all data from Firebase database along with their respective IDs? Currently, I have two functions - getAll() and get(input) that retrieve specific products based on the given ID. However, my current implementation only returns obje ...

Passing an array from a parent component to a child component in Angular

Just to give you some background, I only started my Angular learning journey about a week ago, so feel free to start from the very beginning. So, how can this be achieved? Inside app.component.ts, there is a standard array that needs to be accessible by m ...

What would be the most optimal method for displaying this text using internationalization (i18n)?

Essentially, I want to showcase the string I am Python, Javascript and Flutter developer.. However, it appears like this: https://i.sstatic.net/PqBKq.png Using the following react component: <Typography gutterBottom variant="h6"> I am & ...

transferring attributes from a higher component to a lower one (modal)

https://i.sstatic.net/tSXb5.png https://i.sstatic.net/H4xmj.png I am relatively new to React and I want to share a detailed problem description: I have a Todo project that consists of multiple interfaces. The main interface displays all the lists, each ...

Using webpack to generate sourcemaps for converting Typescript to Babel

Sharing code snippets from ts-loader problems may be more suitable in this context: Is there a way to transfer TypeScript sourcemaps to Babel so that the final sourcemap points to the original file rather than the compiled TypeScript one? Let's take ...

Organizing Firebase functions: Managing multiple functions and dependencies

Objective I aim to gain a deeper understanding of how the firebase CLI manages the deployment process for multiple firebase functions, each stored in different files, and how it handles dependencies that are specific to certain functions. Situation If I ...

Guidelines for segregating a Union from an Array

I'm currently utilizing graphql-code-generator to automatically generate TypeScript definitions from my GraphQL queries. I have a specific union within an array that I am trying to extract in TypeScript. Is this feasible? Although I came across an exa ...

The ngOnChanges lifecycle hook does not trigger when the same value is updated repeatedly

Within my appComponent.ts file, I have a property called: this._userMessage Afterwards, I pass it to the childComponent like so: <child-component [p_sUserMessage]='_userMessage'></child-component> In the childComponent.ts file: @ ...

Tips for importing a .geojson document in TypeScript using webpack?

I am trying to extract data from a .geojson file but faced some challenges while attempting two different methods: const geojson = require('../../assets/mygeojson.geojson'); The first method resulted in an error message stating: Module parse f ...

What is causing the ESLint error when trying to use an async function that returns a Promise?

In my Next.js application, I have defined an async function with Promise return and used it as an event handler for an HTML anchor element. However, when I try to run my code, ESLint throws the following error: "Promise-returning function provided t ...

Is it advisable for a component to handle the states of its sub-components within the ngrx/store framework?

I am currently grappling with the best strategy for managing state in my application. Specifically, whether it makes sense for the parent component to handle the state for two subcomponents. For instance: <div> <subcomponent-one> *ngIf=&qu ...

Is it possible to utilize a variable for binding, incorporate it in a condition, and then return the variable, all while

There are times when I bind a variable, use it to check a condition, and then return it based on the result. const val = getAttribute(svgEl, "fill"); if (val) { return convertColorToTgml(val); } const ancestorVal = svgAncestorValue(svgEl, "fill"); if (a ...

How can we create a versatile Action type in typescript that can accommodate varying numbers of arguments and argument types?

When working with Typescript, encountering a duplicate type error can be frustrating. For instance, consider the following code snippet: export type Action<T> = (arg:T) => void export type Action<T1,T2> = (arg1:T1, arg2:T2) => void How c ...

Ways to declare the function prototype using object and key as parameters

I am currently working on defining a utility function that will handle axios errors and store the resulting error message into a specific field of a specified object. The desired syntax for using this function is: axios.get(...).then(...).catch(ParseIntoE ...

The error "ReferenceError: window is not defined" occurs when calling client.join() due to

I am looking to create a video call application using React and Next.js with the AgoraRTC SDK. After successfully running AgoraRTC.createClient(), AgoraRTC.createStream(), and client.init(), I encountered an error when trying to execute client.join(). The ...

troubleshooting issues with nextjs13 and styledcomponent

Greetings! Our team has recently updated to next.js 13 and react 18, and integrated styled components with the next config setting. However, we have encountered some unusual behaviors. One issue arises when extending styles, as shown below: const CardWra ...

What are the steps for importing a file into a React app that is built using Create React App as plain text?

Objectives I aim to showcase code snippets from the project itself for reference. I intend to keep the displayed code up-to-date with its implementation. I prefer not to remove myself from create-react-app This React project, built using create-react-ap ...

Guide on setting up Material UI with the latest experimental `app/` directory in Next.js

The documentation offers a sample here for material-next-ts. Unfortunately, I was unable to set this up in the recently introduced experimental app/ directory. Can anyone clarify what is the corresponding file for _app.ts or _document.ts in the new app/ ...

A guide on utilizing Material UI Fade for smoothly fading in a component when a text field is selected

I am facing an issue with a text field input and a helper component. My goal is to have the helper component fade in when a user focuses on the input field. The helper component is wrapped as follows: <Fade in={checked}> <DynamicHelperText lev ...