Mocking file input in React TestUtils

蹲街弑〆低调 提交于 2020-01-03 07:06:05

问题


I have a component with a following render f-tion:

  render: function() {
   <input
    type="file"
    name: this.props.name,
    className={this.props.className}
    onChange={this.props.handleChange}
    accept={this.props.accept}/>
 }

State is managed by a container which uploads the file server-side using jquery AJAX call:

 getInitialState: function() {
   return {
     uploaded: false
  };
}

handleChange: function(event) {
event.preventDefault();

var file = event.target.files[0];
if (!file) {
  return;
}

var reader = new FileReader();
reader.readAsText(file, 'UTF-8');
var self = this;

reader.onload = function(e) {
  var content = e.target.result;

 var a =  $.ajax({
    type: 'PUT',
    url: 'http://localhost:8080/upload',
    contentType: 'application/json',
    dataType: "json",
    data: JSON.stringify({
      "input": content
    })
  })
  .fail(function(jqXHR, textStatus, errorThrown) {
    console.log("ERROR WHEN UPLOADING");
  });

 $.when(a).done(function() {
      self.setState({
      uploaded: true,
      });
  });

  } 
} 

This works flawlessly with the server running. However I'd like to test without a need to invoke the server. Here's the Mocha test I have written so far:

var React = require('react');
var assert = require('chai').assert;
var TestUtils = require('react-addons-test-utils');
var nock = require("nock");
var MyContainer = require('../containers/MyContainer');

describe('assert upload', function () {
  it("user action", function () {

    var api = nock("http://localhost:8080")
        .put("/upload", {input: "input"})
        .reply(200, {
        });

  var renderedComponent = TestUtils.renderIntoDocument(
          <MyContainer />
  );

  var fileInput = TestUtils.findAllInRenderedTree(renderedComponent,
           function(comp) { 
                           return(comp.type == "file");
                          });

 var fs = require('fs') ;
 var filename = "upload_test.txt"; 
 var fakeF = fs.readFile(filename, 'utf8', function(err, data) {
    if (err) throw err;
 });

  TestUtils.Simulate.change(fileInput, { target: { value: fakeF } });

  assert(renderedComponent.state.uploaded === true);
  });
});

which fails with a very sad:

TypeError: Cannot read property '__reactInternalInstance$sn5kvzyx2f39pb9' of undefined

来源:https://stackoverflow.com/questions/36752434/mocking-file-input-in-react-testutils

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!