类型错误:ShallowWrapper::state("isOpen") 要求`state` 不是`null` 或`undefined`

IT技术 reactjs unit-testing enzyme
2021-05-10 23:39:06

我一直在尝试运行单元测试,但我不断收到此错误:

TypeError: ShallowWrapper::state("isOpen") 要求state不是nullundefined

我看到过类似的东西并且能够修复它 - 但我目前不知道这是哪里出了问题

使用 React JS - JEST 和 ENZYME

here is the main file js


         closeModal = () => {
    //If close qfmodal, set modalvalues back to values
    let quickfilterModalValues = 
  Object.assign({},this.state.quickfilterValues);
    this.setState({
      selectedRecon_UID: null,
      refreshModalOpen: false, 
      descriptionModalOpen: false, 
      quickFilterModalOpen: false,

       <Modal isOpen={this.state.quickFilterModalOpen} style={descriptionModalStyle}>
      <div>
        <div className='fullmodal'>
          <div className='sidemodal_addnew_x' onClick={this.closeModal}>
            <FontAwesome name='xbutton' className='fa-times' />
          </div>
        </div>    


   Here is the file.test.js  

我没有在这里包括描述和 beforeEach() 测试 -

  // defining this.props
  const baseProps = { 
  onClick,
  isOpen:false,
  }

 it("renders a modal portal", () => {
  const isOpen = wrapper.state("isOpen");
  const modalPortal = wrapper.find("div.fullmodal");
  expect(isOpen).toBeTruthy;
  expect(modalPortal).toHaveLength(1);
  expect(toJson(wrapper)).toMatchSnapshot();
});

我希望我的快照也能渲染 MODAL

1个回答

此错误是由于state未定义组件中的 。

如果您state在类构造函数中定义(或作为实例属性),则不会发生此错误。

例子:

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {/* initial state */}
  }
}

您可以调试是否instance在测试中使用酶的函数定义了状态

console.log(wrapper.instance().state);

如果打印出nullundefined,则您没有正确地将状态对象定义到实例上。

如果它返回一个有效的对象,那么您应该不会看到ShallowWrapper::state("isOpen")错误。