如何测试传递对象作为道具的组件?

How to test component on passing object as props?

FileUploadStatus.test.js

import React from 'react';
import { shallow } from 'enzyme';
import FileUploadStatus from './FileUploadStatus';
import { expect, jest } from '@jest/globals';
import toJson from 'enzyme-to-json';
import { FileResponse } from '../../constants/mockdata';
describe('Page File upload status component', () => {
  const fn = jest.fn();
  it('Should test File upload status component', () => {
    let props;
    let FileUploadRespData;
    beforeEach(() => {
      FileUploadRespData = {
        uploadResp: { ...FileResponse },
        fileHead: 'IRI File Upload Status:',
      };
    });
    const wrapper = shallow(<FileUploadStatus {...FileUploadRespData} />);
    expect(wrapper).toMatchSnapshot();
  });
});

mockdata.js

export const FileResponse = {
  linesProcessed: 0,
  invalidLineList: [
    {
      lineNumber: 0,
      invalidLine:
        "CSVRecord [comment='null', recordNumber=2, values=[CARR GOTTSTEIN 1834 : 2029 AIRPORT BEACH RD, ALEUTIANS WEST, AK, KELLCO PC PRINGLES - TEST, 12345, 4.912095761, 0.379420315]]",
      invalidLineReason: 'Unknown TD Linx ID (12345)',
    },
  ],
};

FileUploadStatus.jsx

import { Grid, makeStyles, Typography } from '@material-ui/core';
import React from 'react';
import '../../../scss/Files.scss';

const useStyles = makeStyles({
  marginTop: {
    marginTop: '3%',
  },
});
function FileUploadStatus({ fileHead, uploadResp }) {
  const classes = useStyles();
  return (
    <div>
      <Typography className='typo'> {fileHead}</Typography>
      <br />

      <span className='message'>Null</span>
      <div className='para'>
        <Typography>
          Lines Processed Successfully: {uploadResp.linesProcessed}
        </Typography>
      </div>
    </div>
  );
}

export default FileUploadStatus;

TypeError: 无法读取未定义的 属性 'linesProcessed'

  18 |       <div className='para'>
  19 |         <Typography>
> 20 |           Lines Processed Successfully: {uploadResp.linesProcessed}
     |                                                     ^
  21 |         </Typography>

我在使用 jest 和 enzyme 进行快照测试时遇到以上错误。我尝试在组件中直接将模拟数据作为 props 传递,但不能 fix.How 我们可以修复它吗?

FileUploadRespDatabeforeEach 移到 it 之外:

let FileUploadRespData;
beforeEach(() => {
  FileUploadRespData = {
    uploadResp: { ...FileResponse },
    fileHead: 'IRI File Upload Status:',
  };
});

it('Should test File upload status component', () => {
  const wrapper = shallow(<FileUploadStatus {...FileUploadRespData} />);
  expect(wrapper).toMatchSnapshot();
});

将您的对象置于 beforeEach() 函数之外:

describe('Page File upload status component', () => {
  const fn = jest.fn();
  it('Should test File upload status component', () => {
    const FileUploadRespData = {
        uploadResp: { ...FileResponse },
        fileHead: 'IRI File Upload Status:',
      };
    const wrapper = shallow(<FileUploadStatus {...FileUploadRespData} />);
    expect(wrapper).toMatchSnapshot();
  });
});