使用React和Enzyme测试文件输入,在模拟事件中为输入提供文件

时间:2019-01-15 09:38:53

标签: reactjs typescript enzyme

使用酶测试我的文件输入组件时遇到了一些困难。文件输入是非常标准的,它调用文件更改函数onChange,它发送的事件需要一个文件数组,并且该文件需要具有该函数的名称,以免出错。该组件在下面;

import * as React from 'react';
import { generateGuid } from '../../../../utilities/GuidGenerator';

export interface Props {
    styles?: Object;
    acceptedExtensions: string;
    fileLoadedFunc: (file: string) => void;
}

const FileInput = ({ styles, acceptedExtensions, fileLoadedFunc }: Props) => {
    var id = generateGuid().slice(0, 6);

    var fileChangedFunc = (e: React.ChangeEvent) => {
        var file = (e.target as HTMLInputElement).files[0];
        if (file) {
            var fileName = file.name.length > 22 ? file.name.slice(0, 16).trimRight().concat("... .", file.name.slice(file.name.length - 3)) : file.name;
            document.getElementById(id).parentElement.previousSibling.childNodes[1].textContent = fileName;
            var reader = new FileReader();
            reader.addEventListener("load", () => {
                fileLoadedFunc(reader.result as string);
            }, false);

            if (file) {
                reader.readAsDataURL(file);
            }
        }
    }

return (
    <div style={styles} className="fileInput" >
        <label htmlFor={id} >
            <i className="zmdi zmdi-upload zmdi-hc-2x" />
            <div>Select File</div>
        </label>
        <div>
            <input accept={acceptedExtensions} id={id} type="file" onChange={(e: React.ChangeEvent) => { fileChangedFunc(e) }} />
        </div>
    </div>
);
}

export default FileInput;

我写的测试在下面。

import * as React from 'react';
import * as Enzyme from 'enzyme';
import * as Adapter from 'enzyme-adapter-react-16';
import FileInput from './FileInput';

Enzyme.configure({ adapter: new Adapter() });

describe('FileInput', () => {
    test('loads in whatever file it\'s given on change event', () => {
        var loadedFile = null;
        var fileInput = Enzyme.mount(<FileInput acceptedExtensions="image/png" fileLoadedFunc={(file: string) => { loadedFile = file }} />);
        fileInput.find('input').at(0).simulate('change', {
            target: {
                files: ['dummyValue.png']
            }
        });
    });
});

此测试导致错误TypeError: Cannot read property 'length' of undefined,因为没有文件名。

要正确地仿真和测试,我将需要在这里实际加载文件,我该怎么做?有没有一种方法可以为change事件提供文件,或者可以给文件输入一个文件路径?

0 个答案:

没有答案