【发布时间】:2018-06-06 09:11:50
【问题描述】:
我在一个组件中有以下代码。我想测试表单的 onSubmit,它在阅读器中调用 this.props.onUpload 方法。 我该如何测试呢? 我的期望测试不起作用,我猜这是因为 this.props.onUpload 在 reader.onload 函数中?
上传表单.js
handleSubmit(e) {
e.preventDefault();
var inputData = '';
var file = this.state.file;
if (file) {
var reader = new FileReader();
reader.onload = (function(file) {
return function(e) {
inputData = e.target.result;
this.props.onUpload(inputData);
};
})(file).bind(this);
reader.readAsText(file);
}
}
render() {
return(
<form onSubmit={this.handleSubmit}>
<label> Enter File: <br/>
<input type="file" id="fileinput" onChange={this.handleChange}/>
</label>
<input type="submit" value="Submit" className="btn-upload" />
</form>
);
}
上传表单.test.js
const mockOnUpload = jest.fn();
const file = new File([""], "filename");
const form = shallow(<UploadForm onUpload={mockOnUpload}/>);
const event = {
preventDefault: jest.fn(),
target: {files : [file]}
};
describe('when clicking `upload-file` button', () => {
beforeEach(() => {
form.find('#fileinput').simulate('change', event);
form.find('form').simulate('submit', event);
});
it('calls the handleSubmit CallBack', () => {
expect(mockOnUpload).toHaveBeenCalledWith(input);
});
});
【问题讨论】:
标签: javascript reactjs tdd jestjs enzyme