反应:在Jest / Enzyme浅层渲染期间无法访问和测试道具和状态

时间:2019-02-14 07:51:21

标签: reactjs jestjs enzyme

我正在尝试在React.js类/组件中测试以下方法的状态操作:

// DataSection.jsx
export default class DataSection extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      initialFetch : true,
      REPORT_OPTION : 'totals',
      viewMarker : 0,
    };
  }


    updateViewMarker = (incrementSize, plusMinusOption) => {
let {viewMarker} = this.state;
console.log(this.props, `=====this.props inside updateViewMarker=====`);
const {preparedReportData} = this.props;

// safe string to math translation
if (plusMinusOption === '-') {
  this.setState({
    viewMarker : viewMarker - incrementSize
  })
} else if (plusMinusOption === '+') {
  this.setState({
    viewMarker : viewMarker + incrementSize
  })
}

我是Enzyme的新手,无法访问状态更新。我以为问题可能出在实例上,所以我对.instance()进行了一些尝试,并收到了我收到的错误。

// DataSection.test.jsx

// component shallow render with dud props
const mockProp = jest.fn();
const shallowDataSection = enzyme.shallow(<DataSection
  dispatchGetDonationData={ mockProp }
  rawReportData={ mockProp }
  preparedReportData={ mockProp }
  dispatchUpdatePreparedReportData={ mockProp }
/>);

test('increments by 10', () => {
    expect(shallowDataSection.instance()).toBeInstanceOf(DataSection); // passes
    expect(shallowDataSection.state().viewMarker).toEqual(0); // passes
    // expect(shallowDataSection.instance().state().viewMarker).toEqual(0); // fails

    shallowDataSection.setProps({
      preparedReportData : [1,1,1,1,1,1,1,1,1,1,1,1]
    }); 
    // shallowDataSection.instance().setProps({
    //   preparedReportData : [1,1,1,1,1,1,1,1,1,1,1,1]
    // }); // setProps is not a function


    expect(shallowDataSection.props().preparedReportData.length).toEqual(12); // can't read property 'length' of undefined
    // expect(shallowDataSection.instance().props().preparedReportData.length).toEqual(12); // shallowDataSection.instance(...).props is not a function

  });

犯了什么错误?下面的代码是我的实际测试,但是我很难获得上述工作的前提条件

// dataSection.instance().updateViewMarker(10, '+');
// expect(shallowDataSection.state().viewMarker).toEqual(20);

编辑:使用的库:

"enzyme": "^3.8.0",
"enzyme-adapter-react-16": "^1.9.1",
"jest-environment-enzyme": "^7.0.1",
"jest-enzyme": "^7.0.1",
"react": "^16.7.0",

导入DataSection.test.js:

const React = require("react"); 
const App = require("../App");
const DataSection = require("../components/DataSection").default;
const dataSection = new DataSection();
const enzyme = require("enzyme");
const Adapter = require("enzyme-adapter-react-16");

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

1 个答案:

答案 0 :(得分:0)

似乎您没有在增量后设置更新状态。 断言状态为0的测试之所以通过,是因为在您最初渲染组件时其状态未定义?