简体   繁体   中英

Jest TypeError: Cannot read property 'id' of undefined

Can`t understend how to specify the id, I am a beginner, I hope to help. the error from the beginning was that: TypeError: Cannot read property '0' of undefined

at first

and path

but when i add to test file mockResolvedValue({allEmployees: '',}) it disappeared and a new one appeared

Js file

loadPage(page, begin = false) {
    const {
      timeSheetsSortParams, filter,
    } = this.state;
    this.setState({ timesheet: [] });
    API.loadTimesheets(page, timeSheetsSortParams, filter).then((res) => {
      const updFilter = begin ? { user: res.allEmployees[0].id } : {};
      this.setState({
        filter: { ...filter, ...updFilter },
        withCheckBox: res.currentEmployee.role === 'superadmin',
        checkedRows: res.timesheets.filter((item) => item.selected === true),
        currentPage: page,
        currentEmployee: res.currentEmployee,
        totalPages: 1,
        timesheetsCount: res.timesheetsCount,
        timeSheets: res.timesheets,
        allEmployees: res.allEmployees,
      });
    });
  }

test.js file

import React from 'react';
import '@testing-library/jest-dom';
import {
  findByText, findByTitle, fireEvent, render, screen,
} from '@testing-library/react';
import userEvent from '@testing-library/user-event';

import Enzyme, { shallow } from 'enzyme';

import Adapter from '@wojtekmaj/enzyme-adapter-react-17';
import API from '../../../services/api';
import TimeSheetsIndex from '../../time_sheets/TimeSheetsIndex';

Enzyme.configure({ adapter: new Adapter() });

describe('TimeSheetsIndex', () => {
  beforeEach(() => {
    jest.spyOn(API, 'loadTimesheets').mockResolvedValue({
      totalPages: 1,
      timesheetsCount: 2,
      ok: true,
      timeSheets: [{
        id: '1',
        employee_id: '1',
        date_week: '2022-08-08',
        date_paid: '',
        status: 'new',
        amount: '200',
        fact_hours: '35',
        rate: '35',
        date_closed: '',
        date_updated: '',
        updater_id: '',
      }, {
        id: '2',
        employee_id: '2',
        date_week: '2022-08-09',
        date_paid: '',
        status: 'updated',
        amount: '400',
        fact_hours: '35',
        rate: '35',
        date_closed: '',
        date_updated: '',
        updater_id: '1',
      }],
      allEmployees: '',
      id: '',
    });
    jest.spyOn(API, 'deleteTimesheet').mockResolvedValue({ ok: true });
    jest.spyOn(API, 'createTimesheet').mockResolvedValue({ ok: true });
  });

  it('renders list of TimeSheets', async () => {
    render(<TimeSheetsIndex />);
    expect(await screen.findByText('TimeSheets (2)')).toBeVisible();

    const rows = await screen.findAllByRole('row');
    expect(rows).toHaveLength(2);

    expect(await findByTitle(rows[1], 'id')).toHaveTextContent('1');
    expect(await findByTitle(rows[1], 'employee_id')).toHaveTextContent('1');
    expect(await findByTitle(rows[1], 'date_week')).toHaveTextContent('2022-08-08');
    expect(await findByTitle(rows[1], 'date_paid')).toBeEmptyDOMElement();
    expect(await findByTitle(rows[1], 'status')).toHaveTextContent('new');
    expect(await findByTitle(rows[1], 'amount')).toHaveTextContent('200');
    expect(await findByTitle(rows[1], 'fact_hours')).toHaveTextContent('35');
    expect(await findByTitle(rows[1], 'rate')).toHaveTextContent('35');
    expect(await findByTitle(rows[1], 'date_closed')).toBeEmptyDOMElement();
    expect(await findByTitle(rows[1], 'date_updated')).toBeEmptyDOMElement();
    expect(await findByTitle(rows[1], 'updater_id')).toBeEmptyDOMElement();
  });
});

error

Firstly, I think the error is caused by const updFilter = begin? { user: res.allEmployees[0].id }: {}; const updFilter = begin? { user: res.allEmployees[0].id }: {}; this line; res.allEmployees might have returned undefined . After you set the value to empty string '' , res.allEmployees is no longer undefined, but since it's an empty string accessing its first index will still return undefined , so you should set the value to an array of objects in order for this test code to work properly.

I assumed that res.allEmployees should have been array, so perhaps you should check the res.allEmployees value (if you received it from external source, but I assumed you mocked it here), or mock it. Adjust the allEmployees value according to your needs. The value I wrote below was assumed from your test code:

allEmployees: [
  {
     "id": 1, 
     "employee_id": 1, 
     // and so on
  }
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM