Wrapper is not defined in Jest

I'm trying to test one of my React components but receive the following error:

ReferenceError: wrapper is not defined
describe('TodaysHabits', () => {
  let component;
  beforeEach(() => {
    wrapper = shallow( < TodayHabits / > );
  });
  test('it exists', () => {
    expect(wrapper).toExist;
  });
  test('it contains an p tag', () => {
    const p = wrapper.find('p');
    expect(p.text()).toBe('this is display habits');
  });
});

index.js

import React from 'react';
import moment from 'moment';
import './todayhabits.css';

class TodayHabits extends React.Component {
  // This component will show the habits that the user has to complete this specific day
  // To do this we need to make a api call to get all habits where they have the respective day as true in the sql
  state = {
    dailyHabits: [],
  }

  //for each habit, it will display a new habit component
  //we need to pass a prop to each habit component containing that habit's id and title

  displayHabits () {
    return <p>this is display habits</p>
  }

  render() {
    return (
      <div id='dailyHabits'>
        { moment().format('dddd') }, <br/>
        { moment().format("Do MMMM YYYY") } <br/>
        {this.displayHabits()}
        <button onClick={() => { history.push(`/newHabit`) }}>Add a habit!</button>
      </div>
    )
  }
}

export default TodayHabits;

I tried doing more research on fixing this error but it wasn't successful.

1 answer

  • answered 2021-01-13 22:03 hafiz ali

    Can you try declaring wrapper as a variable?

    You're not declaring the variable and directly assigning a value to it.

    describe('TodaysHabits', () => {
      let component;
      let wrapper;
      beforeEach(() => {
        wrapper = shallow( < TodayHabits / > );
      });
      test('it exists', () => {
        expect(wrapper).toExist;
      });
      test('it contains an p tag', () => {
        const p = wrapper.find('p');
        expect(p.text()).toBe('this is display habits');
      });
    });