小编典典

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

reactjs

我想测试我的React组件是否可以用来FileReader<input type="file"/>元素中导入用户选择文件的内容。我的以下代码显示了一个工作正常且测试失败的组件。

在我的测试中,我尝试使用Blob代替文件,因为Blob也可以被读取FileReader。那是有效的方法吗?我还怀疑问题的一部分reader.onload是异步的,我的测试需要考虑到这一点。我需要在某个地方许下诺言吗?或者,我是否可能需要模拟FileReader使用jest.fn()

我真的更喜欢只使用标准的React堆栈。特别是我想使用Jest和Enzyme,而不必使用Jasmine或Sinon等。但是,如果您知道Jest /
Enzyme 无法 完成某些工作,而又 可以 通过其他方式完成,那也可能会有所帮助。

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 <input type="file" onChange={this.changeHandler}/>;
    }
}
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(<MyComponent/>).find('input')
        .simulate('change', { target: { files: [ blob ] } });
    expect(this.state('fileContents')).toBe('foo');
});

阅读 394

收藏
2020-07-22

共1个答案

小编典典

此答案显示了 如何 使用jest访问代码的所有不同部分。但是,这并不一定意味着 应该 以这种方式测试所有这些部分。

代码被测基本上相同,不同之处在于我已被取代的问题addEventListener('load', ...onload = ...,我已删除了console.log行:

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 <input type="file" onChange={this.changeHandler}/>;
    }
}
export default MyComponent;

我相信我已经设法测试了被测代码中的几乎所有内容(注释中指出了一个例外,下面将进一步讨论),其内容如下:

MyComponent.test.js

import React from 'react';
import {mount} from 'enzyme';
import MyComponent from './temp01';

it('should test handler', () => {
    const componentWrapper   = mount(<MyComponent/>);
    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
});

我尚未明确测试的一件事是是否changeHandler被调用。这似乎很容易,但无论出于何种原因,它仍然使我难以理解。它清楚地
被调用,其他功能嘲笑 之内
就被证实已经被调用但我还没能检查自己是否是所谓的,或者使用jest.fn()甚至茉莉花的spyOn

2020-07-22