简体   繁体   English

如何使用Jest测试FileReader

[英]How to test FileReader using Jest

I am trying to get 100% coverage in my test and it this one passes but then it still highlights the render.onload function 我试图在我的测试中获得100%的覆盖率,并且这一测试通过了,但是仍然突出了render.onload函数

Component.jsx: Component.jsx:

handleInputChange = (evt) => {
  evt.preventDefault();
  const { target } = evt;
  let value;
  let self = this;
  const reader = new FileReader();
  reader.onload = function (evt) {
    self.setState({
      previewPicture: evt.target.result,
      error: null
    });
  };
  reader.readAsDataURL(target.files[0]);
  value = target.files[0];          
  const name = target.name;
  this.setState({
    [name]: value
  });
};

Test: 测试:

    const evt = {
      target: {
        type: 'file',
        name: 'profilePicture',
        files: [{ name: 'testName' }]
      },
      preventDefault: jest.fn()
    };
    const component = mount(<Component {...props} />).instance();
    evt.target.files[0] = new Blob([evt.target.files[0]], {type : 'img/png'});
    component.handleInputChange(evt);
    expect(component.state.profilePicture).toEqual(file);
});

I want to have all covered in the test but I dont know test the FileRader 我想在测试中涵盖所有内容,但我不知道测试FileRader

You dont need to test other component's behavior in the scope of your component. 您无需在组件范围内测试其他组件的行为。

So, if you are developing a component that uses FileReader() you must assume that FileReader() is working properly. 因此,如果要开发使用FileReader()的组件,则必须假定FileReader()正常工作。 FileReader() must have it own tests to guarantee that its behavior is also working well, this way we keep the responsability of each component in the scope of its implementation. FileReader()必须具有自己的测试,以确保其行为也能正常工作,这样我们就可以在实现范围内保持每个组件的责任。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM