Home > Blockchain >  Apollo mocked provider not sending data when testing with Jest
Apollo mocked provider not sending data when testing with Jest

Time:10-02

I'm working on testing some of my client graphql code. For some reason, I know I'm passing the correct data down to the component, however, when I log the variables before and after it gets to the component, they look completely different.

Here's the test:

const mocks = [
  {
    request: {
      query: GET_ENTERPRISE_CLAIMS,
    },
    result:() => {
      const value = {
        data: {
          getPersonalNetworkClaimsList: {
            personalNetworkClaims: [
              { 
                startDate: '22/22/2222', 
                careProvider: 'JerryAtricks', 
                type: 'PET', 
                status: { 
                  value: 'PENDING' 
                } 
              },
              { 
                startDate: '22/22/2222', 
                careProvider: 'SimoneCharles', 
                type: 'ADULT', 
                status: { 
                  value: 'APPROVED' 
                } 
              },
              { 
                startDate: '22/22/2222', 
                careProvider: 'JerryKrause', 
                type: 'CHILD', 
                status: { 
                  value: 'PAID_MANUALLY' 
                } 
              },
              { 
                startDate: '22/22/2222', 
                careProvider: 'MichaelJordan', 
                type: 'ADULT', 
                status: { 
                  value: 'PENDING_VERBAL_CONFIRMATION' 
                } 
              },
            ],
          }
        },
      }
      console.log(JSON.stringify(value));
      return value;
    } 
  }
]

describe('ViewClaims', () => {
  
  it('renders the table', async () => {
    render(
      <MockedProvider mocks={mocks} addTypename={false}>
        <ViewClaims />
      </MockedProvider>
    );
    
    await act(async () => {
      await new Promise((resolve) => setTimeout(resolve, 0));
    });
    
    expect(screen.getByText('JerryAtricks')).toBeInTheDocument();
  });
});

And here's my component:

import { makeStyles, Button, useTheme, Box, Typography, Link } from '@material-ui/core';
import { GET_ENTERPRISE_CLAIMS } from '@/components/request/GQL';
import { useQuery } from '@apollo/client';

interface claims {
  getPersonalNetworkClaimsList: networkClaimsList
}

interface networkClaimsList {
  personalNetworkClaims: personalNetworkClaim[]
}

interface personalNetworkClaim {
  careProvider: string,
  id: string,
  startDate: string,
  status: claimStatus,
  type: string
}

interface claimStatus {
  value: string
}

export default function ViewClaims() {
  // TODO:
  const { data } = useQuery<claims>(GET_ENTERPRISE_CLAIMS);
  console.log(JSON.stringify(data));
  const theme = useTheme();
  const useStyles = makeStyles(() => ({
    root: {
      padding: theme.spacing(3, 2),
      overflowX: 'hidden',
      flex: '1 0 auto',
      [theme.breakpoints.up('md')]: {
        padding: theme.spacing(6, 3),
      },
      maxWidth: '1280px',
      margin: 'auto',
      width: '100%',
    },
    column: {
      fontWeight: 'bold',
    },
    items: {
      width: '25%',
    },
    itemsCenter: {
      textAlign: 'center',
      width: '25%',
    },
    itemsLast: {
      width: '25%',
      textAlign: 'end',
    },
    bannerWrapper: {
      display: 'flex',
      justifyContent: 'space-between',
      alignItems: 'center',
      height: '160px',
      background: '#FBF3EC',
      width: '100%',
    },
    bannerImage: {
      height: '100%',
      width: 'auto',
      position: 'absolute',
      right: '0',
    },
    contentWrapper: {
      width: '100%',
      maxWidth: '1024px',
      margin: 'auto',
    },
    tableClasses: {
      width: '100%',
      borderCollapse: 'collapse',
      borderSpacing: '0',
    },
    leftAlignedCol: {
      textAlign: 'left',
      width: '25%',
    },
    rightAlignedCol: {
      textAlign: 'right',
      width: '25%',
    },
    centerAlignedCol: {
      textAlign: 'center',
      width: '25%',
    },
    tableData: {
      paddingTop: '10px',
      paddingBottom: '10px',
    },
    tableRowBorder: {
      borderBottom: '1px solid #CCD1D6',
    },
    addAClaimBtn: {
      marginTop: '36px',
      display: 'flex',
      justifyContent: 'flex-end',
      width: '100%',
      [theme.breakpoints.down('sm')]: {
        justifyContent: 'center',
      },
    },
  }));
  const classes = useStyles();

  function handleAddAClaimClick() {
    // TODO
  }

  function getCareTypeNamesFromData(careType: string) {
    if (careType.toLocaleLowerCase().includes('child')) {
      return 'Child';
    } else if (careType.toLocaleLowerCase().includes('adult')) {
      return 'Adult';
    } else if (careType.toLocaleLowerCase().includes('pet')) {
      return 'Pet';
    } else {
      // unknown type. Throw Sentry error.
      return '--';
    }
  }

  function mapStatusToDisplayValue(value: string) {
    if (value.length) {
      return value.charAt(0).toLocaleUpperCase()   value.slice(1).replaceAll('_', ' ').toLocaleLowerCase();
    }
    return value;
  }

  return (
    <>
      <table className={classes.tableClasses}>
        <thead>
          <tr>
            <th className={classes.leftAlignedCol}>
              <Typography variant="inherit">Date Submitted</Typography>
            </th>
            <th className={classes.centerAlignedCol}>
              <Typography variant="inherit">Care Type</Typography>
            </th>
            <th className={classes.centerAlignedCol}>
              <Typography variant="inherit">Provider Name</Typography>
            </th>
            <th className={classes.rightAlignedCol}>
              <Typography variant="inherit" component="span">
                Status
              </Typography>
            </th>
          </tr>
        </thead>
        <tbody>
          {data?.getPersonalNetworkClaimsList?.personalNetworkClaims?.map((claim, i) => {
            const rowHasBorder = i < data.getPersonalNetworkClaimsList.personalNetworkClaims.length - 1;
            return (
              <tr className={`${rowHasBorder ? classes.tableRowBorder : ''}`} key={claim.id}>
                <td className={`${classes.leftAlignedCol} ${classes.tableData}`}>
                  <Typography variant="body2">{claim.startDate}</Typography>
                </td>
                <td className={`${classes.centerAlignedCol} ${classes.tableData}`}>
                  <Typography variant="body2">{getCareTypeNamesFromData(claim.type)}</Typography>
                </td>
                <td className={`${classes.centerAlignedCol} ${classes.tableData}`}>
                  <Typography variant="body2">{claim.careProvider}</Typography>
                </td>
                <td className={`${classes.rightAlignedCol} ${classes.tableData}`}>
                  {/* TODO: Link to new view at this point */}
                  <Link href="#">{mapStatusToDisplayValue(claim.status.value)}</Link>
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
      <Box className={classes.addAClaimBtn}>
        <Button
          id="continue"
          color="primary"
          variant="contained"
          onClick={handleAddAClaimClick}
          disabled={false}
          itemID="addAClaimBtn"
        >
          Add a claim
        </Button>
      </Box>
    </>
  );
}

When I run the test, I get a console log in the mocks' result function showing all the items as expected. However, when the console log from the component is run, it shows this:

// in mocks result function
{"data":{"getPersonalNetworkClaimsList":{"personalNetworkClaims":[{"startDate":"22/22/2222","careProvider":"JerryAtricks","type":"PET","status":{"value":"PENDING"}},{"startDate":"22/22/2222","careProvider":"SimoneCharles","type":"ADULT","status":{"value":"APPROVED"}},{"startDate":"22/22/2222","careProvider":"JerryKrause","type":"CHILD","status":{"value":"PAID_MANUALLY"}},{"startDate":"22/22/2222","careProvider":"MichaelJordan","type":"ADULT","status":{"value":"PENDING_VERBAL_CONFIRMATION"}}]}}}
// within component
{"getPersonalNetworkClaimsList":{}}

And here is the query:

const GET_ENTERPRISE_CLAIMS = gql`
  {
    getPersonalNetworkClaimsList {
      ... on PersonalNetworkClaimSuccess {
        personalNetworkClaims {
          id
          startDate
          careProvider
          type
          status {
            value
          }
        }
      }
    }
  }
`;

Any ideas on why my component isn't loading any of the data? Thanks.

CodePudding user response:

Try to specify variables on request object, although the request does not use any variable:

request: {
  query: GET_ENTERPRISE_CLAIMS,
  variables: {},
},

when you mock the response there should be value for every attribute you request, the id is missing in the elements of array personalNetworkClaims, try adding id for single one

  • Related