【问题标题】:Wrapper is not defined in Jest包装器没有在 Jest 中定义
【发布时间】:2021-01-13 21:34:31
【问题描述】:

我正在尝试测试我的一个 React 组件,但收到以下错误:

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;

我尝试对修复此错误进行更多研究,但没有成功。

【问题讨论】:

    标签: javascript reactjs testing jestjs enzyme


    【解决方案1】:

    您可以尝试将wrapper 声明为变量吗?

    您没有声明变量并直接为其赋值。

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

    【讨论】:

    • 你能分享整个测试文件吗?
    • 问题中的代码是整个测试文件。
    • 我又更新了,你能再试一次吗?我已经在上面的范围内定义了包装器
    • 你是从酶进口浅的吗?像这样import { shallow } from 'enzyme';
    • 嗨,谢谢你摆脱了错误,但现在我得到一个不同的错误,即“.find”未定义“TypeError:无法读取未定义的属性'find'”这行代码" test('它包含一个 p 标签', () => { > 13 | const p = wrapper.find('p');"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-12
    • 1970-01-01
    • 2020-08-27
    • 1970-01-01
    相关资源
    最近更新 更多