0
votes

I have a function that returns different component based on the screen size.

The code is as follows.

in Payment component

 const renderSection= () => {
        if (isMobile) {
          return <Total/>;
        } else {
          return (
            <Order/>
          );
        }
      };

    <div className={classes.section} data-testid="payment">{renderSection()}</div>
    

I have written a test as follows

 it('should render total in mobile view', () => {
    (useViewport as jest.Mock).mockImplementationOnce(() => VIEWPORTS.SM || VIEWPORTS.XS);
    const { getByTestId } = render(
      <Provider store={store}>
        <ThemeProvider theme={theme}>
          <Payment/>
        </ThemeProvider>
      </Provider>,
    );
    const payment = getByTestId('payment');

    /// i want to do something like this
    expect(payment).toEqual('Total');
  });

I want to check if the screen size is mobile it renders Total component and if not the Order component. How do i get the component name (or anyother way that i can identify the rendered component) with the implementation i have done above?

1

1 Answers

0
votes

You could assign a data-testid to the containers in your Total and Order components and check which one is displayed:

In <Total>:

<div data-testid="total">
    ...{/* Rest of JSX */}

In <Order>:

<div data-testid="order">
    ...{/* Rest of JSX */}

Then in your test use the getByTestId query to check if a view is visible:

it('should render total in mobile view', () => {
    (useViewport as jest.Mock).mockImplementationOnce(() => VIEWPORTS.SM || VIEWPORTS.XS);
    const { getByTestId } = render(
      <Provider store={store}>
        <ThemeProvider theme={theme}>
          <Payment/>
        </ThemeProvider>
      </Provider>,
    );
    const payment = getByTestId('payment');

    // When `<Total>` should be displayed
    expect(getByTestId('total')).toBeVisible();

    // When `<Order>` should be displayed
    expect(getByTestId('order')).toBeVisible();
  });