TypeError:ShallowWrapper::state("isOpen") 要求 `state` 不能为 `null` 或 `undefined`

2023-12-27

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

TypeError: ShallowWrapper::state("isOpen") 要求state not be null or undefined

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

使用 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


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

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

Example:

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

您可以调试是否使用酶定义了状态instance在你的测试中发挥作用:

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

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

如果返回一个有效的对象,那么你不应该看到ShallowWrapper::state("isOpen") error.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

TypeError:ShallowWrapper::state("isOpen") 要求 `state` 不能为 `null` 或 `undefined` 的相关文章

随机推荐