Apollo 嘲笑提供者在使用 Jest 进行测试时不发送数据

Apollo mocked provider not sending data when testing with Jest

我正在测试我的一些客户端 graphql 代码。出于某种原因,我知道我正在将正确的数据传递给组件,但是,当我在它到达组件之前和之后记录变量时,它们看起来完全不同。

这是测试:

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();
  });
});

这是我的组件:

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>
    </>
  );
}

当我 运行 测试时,我在模拟的结果函数中得到一个控制台日志,显示了预期的所有项目。但是,当组件的控制台日志为 运行 时,它会显示:

// 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":{}}

这里是查询:

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

关于为什么我的组件没有加载任何数据的任何想法?谢谢

尝试在请求对象上指定变量,尽管请求不使用任何变量:

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

当你模拟响应时,你请求的每个属性都应该有值,数组 personalNetworkClaims 的元素中缺少 id,尝试为单个元素添加 id