vendredi 25 septembre 2020

Writing a Jest Test for a React Component that has child components that use Context

The child components are expecting a "prices" array in a test I'm writing with Jest for a React app. The test is throwing an error:

Cannot read property 'map' of undefined

I've tried hardcoding the components/values as well as passing prices values in several different ways but have been unable to get them to reach the child components.



Here is the component I need to write a test for:

import React from 'react';
import styled from 'styled-components';
import { AppContext } from '../App/AppProvider';
import PriceSquare from './PriceSquare';

const PriceGrid =  styled.div`
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  grid-gap: 15px;
  margin-top: 40px;
`

export default function() {
  return (
    <AppContext.Consumer>
      {({prices}) => (
        <PriceGrid>
          {prices.map((price, index) => (
            <PriceSquare key={`priceSquare-${index}`} index={index} price={price} />
          ))}
        </PriceGrid>
      )}
    </AppContext.Consumer>
  );
}



Here is the attempted test I've written:

import React from 'react';
import ReactDOM from 'react-dom';
import { AppContext, AppProvider } from '../App/AppProvider';
import PriceGrid from './PriceGrid';

const TestContext = React.createContext();

describe('PriceGrid Component', () => {
  it('renders without crashing', () => {
    const div = document.createElement('div');
    ReactDOM.render(
      <AppProvider>
      <AppContext.Consumer>
          {({ prices }) => (
              <PriceGrid />
          )}
      </AppContext.Consumer>
      </AppProvider>, div);
    ReactDOM.unmountComponentAtNode(div);
  });
});



Here is the error I'm getting:

 FAIL  src/Dashboard/PriceGrid.test.js
  ● PriceGrid Component › renders without crashing

    TypeError: Cannot read property 'map' of undefined

      16 |       {({prices}) => (
      17 |         <PriceGrid>
    > 18 |           {prices.map((price, index) => (
         |                   ^
      19 |             <PriceSquare key={`priceSquare-${index}`} index={index} price={price} />
      20 |           ))}
      21 |         </PriceGrid>

Aucun commentaire:

Enregistrer un commentaire