实例在Jest中安装的连接组件返回NULL

时间:2019-03-25 06:17:01

标签: reactjs react-redux jestjs enzyme ref

对于任何不适合行话的术语,我都比较反应和道歉。

我正在尝试测试由ref变量组成的连接组件的原型方法,如下所示:

app.js

export class Dashboard extends React.Component { // Exporting here as well
  constructor(props) {
    this.uploadFile = React.createRef();

    this.uploadJSON = this.uploadJSON.bind(this);
  }

  uploadJSON () { 
     //Function that I am trying to test
     //Conditions based on this.uploadFile
  }
render() {
    return (
      <div className="dashboard wrapper m-padding">
        <div className="dashboard-header clearfix">
          <input
            type="file"
            ref={this.uploadFile}
            webkitdirectory="true"
            mozdirectory="true"
            hidden
            onChange={this.uploadJSON}
            onClick={this.someOtherFn}
          />
        </div>
        <SensorStatList />
        <GraphList />
      </div>
    );
  }

  const mapStateToProps = state => ({
    //state
  });

  const mapDispatchToProps = dispatch => ({
    //actions
  });

  export default connect(
    mapStateToProps,
    mapDispatchToProps
  )(Dashboard);
}

此处,SensorStatListGraphList是功能组件,也使用redux连接。

经过研究后,我的测试文件达到了这一水平:

app.test.js

import { Dashboard } from '../Dashboard';
import { Provider } from 'react-redux';
import configureStore from '../../../store/store';

const store = configureStore();

export const CustomProvider = ({ children }) => {
    return (
      <Provider store={store}>
        {children}
      </Provider>
    );
  };

describe("Dashboard", () => {

    let uploadJSONSpy = null;

    function mountSetup () {
        const wrapper = mount(
                <CustomProvider>
                  <Dashboard />
                </CustomProvider>
              );
        return {
            wrapper
        };
    }

    it("should read the file", () => {
        const { wrapper } = mountSetup();
        let DashboardWrapper = wrapper;

        let instance = DashboardWrapper.instance();

        console.log(instance.ref('uploadFile')) // TypeError: Cannot read property 'ref' of null
    })

有人可以帮助我理解为什么出现此错误

  

console.log(instance.ref('uploadFile'))   // TypeError:无法读取null的属性'ref'

弹出?另外,这种方法是否还好?如果没有,有什么更好的选择?

1 个答案:

答案 0 :(得分:1)

wrapperCustomProvider,没有实例,而ref应该与不推荐使用的字符串引用一起使用。

如果应该在Dashboard上访问引用,可以是:

wrapper.find(Dashboard).first().instance().uploadFile.current

如果应该访问输入包装器,它可以是:

wrapper.find('input').first()