如何使用Jest/Ezyme测试React中输入的文件类型的更改处理程序?

您所在的位置:网站首页 无人机测绘吧贴吧 如何使用Jest/Ezyme测试React中输入的文件类型的更改处理程序?

如何使用Jest/Ezyme测试React中输入的文件类型的更改处理程序?

2024-07-15 15:16:35| 来源: 网络整理| 查看: 265

百度翻译此文   有道翻译此文 问题描述

I want to test whether my React component can use FileReader to import the contents of a user-selected file from an element. My code below shows a working component with a broken test.

In my test I'm attempting to use a blob as a substitute for the file because blobs can also be "read" by FileReader. Is that a valid approach? I also suspect that part of the issue is that reader.onload is asynchronous and that my test needs to take this into consideration. Do I need a promise somewhere? Alternatively, do I perhaps need to mock FileReader using jest.fn()?

I would really prefer to only use the standard React stack. In particular I want to use Jest and Enzyme and not have to use, say, Jasmine or Sinon, etc. However if you know something can't be done with Jest/Enzyme but can be done another way, that might also be helpful.

MyComponent.js:

import React from 'react'; class MyComponent extends React.Component { constructor(props) { super(props); this.state = {fileContents: ''}; this.changeHandler = this.changeHandler.bind(this); } changeHandler(evt) { const reader = new FileReader(); reader.onload = () => { this.setState({fileContents: reader.result}); console.log('file contents:', this.state.fileContents); }; reader.readAsText(evt.target.files[0]); } render() { return ; } } export default MyComponent;

MyComponent.test.js:

import React from 'react'; import {shallow} from 'enzyme'; import MyComponent from './MyComponent'; it('should test handler', () => { const blob = new Blob(['foo'], {type : 'text/plain'}); shallow().find('input') .simulate('change', { target: { files: [ blob ] } }); expect(this.state('fileContents')).toBe('foo'); }); 推荐答案

This answers shows how to access all of the different parts of the code using jest. However, it doesn't necessarily mean that one should test all of these parts this way.

The code-under-test is essentially the same as in the question except that I have substituted addEventListener('load', ... for onload = ..., and I have removed the console.log line:

MyComponent.js:

import React from 'react'; class MyComponent extends React.Component { constructor(props) { super(props); this.state = {fileContents: ''}; this.changeHandler = this.changeHandler.bind(this); } changeHandler(evt) { const reader = new FileReader(); reader.addEventListener('load', () => { this.setState({fileContents: reader.result}); }); reader.readAsText(evt.target.files[0]); } render() { return ; } } export default MyComponent;

I believe I've managed to test just about everything in the code-under-test (with the one exception noted in the comments and discussed further below) with the following:

MyComponent.test.js:

import React from 'react'; import {mount} from 'enzyme'; import MyComponent from './temp01'; it('should test handler', () => { const componentWrapper = mount(); const component = componentWrapper.get(0); // should the line above use `componentWrapper.instance()` instead? const fileContents = 'file contents'; const expectedFinalState = {fileContents: fileContents}; const file = new Blob([fileContents], {type : 'text/plain'}); const readAsText = jest.fn(); const addEventListener = jest.fn((_, evtHandler) => { evtHandler(); }); // WARNING: But read the comment by Drenai for a potentially serious // problem with the above test of `addEventListener`. const dummyFileReader = {addEventListener, readAsText, result: fileContents}; window.FileReader = jest.fn(() => dummyFileReader); spyOn(component, 'setState').and.callThrough(); // spyOn(component, 'changeHandler').and.callThrough(); // not yet working componentWrapper.find('input').simulate('change', {target: {files: [file]}}); expect(FileReader ).toHaveBeenCalled ( ); expect(addEventListener ).toHaveBeenCalledWith('load', jasmine.any(Function)); expect(readAsText ).toHaveBeenCalledWith(file ); expect(component.setState).toHaveBeenCalledWith(expectedFinalState ); expect(component.state ).toEqual (expectedFinalState ); // expect(component.changeHandler).toHaveBeenCalled(); // not yet working });

The one thing I haven't explicitly tested yet is whether or not changeHandler was called. This seems like it should be easy but for whatever reason it is still eluding me. It clearly has been called, as other mocked functions within it are confirmed to have been called but I haven't yet been able to check whether it itself was called, either using jest.fn() or even Jasmine's spyOn. I have asked this other question on SO to try to address this remaining problem.



【本文地址】

公司简介

联系我们

今日新闻


点击排行

实验室常用的仪器、试剂和
说到实验室常用到的东西,主要就分为仪器、试剂和耗
不用再找了,全球10大实验
01、赛默飞世尔科技(热电)Thermo Fisher Scientif
三代水柜的量产巅峰T-72坦
作者:寞寒最近,西边闹腾挺大,本来小寞以为忙完这
通风柜跟实验室通风系统有
说到通风柜跟实验室通风,不少人都纠结二者到底是不
集消毒杀菌、烘干收纳为一
厨房是家里细菌较多的地方,潮湿的环境、没有完全密
实验室设备之全钢实验台如
全钢实验台是实验室家具中较为重要的家具之一,很多

推荐新闻


图片新闻

实验室药品柜的特性有哪些
实验室药品柜是实验室家具的重要组成部分之一,主要
小学科学实验中有哪些教学
计算机 计算器 一般 打孔器 打气筒 仪器车 显微镜
实验室各种仪器原理动图讲
1.紫外分光光谱UV分析原理:吸收紫外光能量,引起分
高中化学常见仪器及实验装
1、可加热仪器:2、计量仪器:(1)仪器A的名称:量
微生物操作主要设备和器具
今天盘点一下微生物操作主要设备和器具,别嫌我啰嗦
浅谈通风柜使用基本常识
 众所周知,通风柜功能中最主要的就是排气功能。在

专题文章

    CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭