});it('should call click event on File Inpu">
正在尝试传递以下单击事件,但不确定如何在document.getElementById('file-input').value
上调用onclick
下面是testfile.js:
beforeEach(() => {
wrapper = shallow(<Component {...baseProps} />
});
it('should call click event on File Input', () => {
baseProps.onClick.mockClear();
wrapper.setProps({});
wrapper.setState({});
wrapper.update();
wrapper.find('#fileinput-testclick').simulate('click');
expect(toJson(wrapper)).toMatchSnapshot();
});
我好像找不到#id
了。有什么原因吗?这是file.js
<label
for="file-input"
id="fileinput-testclick"
onClick={() => {
document.getElementById('file-input').value = '';
document.getElementById('file-input').click();
}}
className="tran-button file-button">
{this.state.fileName ? 'Change File' : 'Choose File'}
</label>;
发布于 2019-11-12 13:21:41
以下是单元测试解决方案:
index.jsx
import React, { Component } from 'react';
class SomeComponent extends Component {
constructor(props) {
super(props);
this.state = {
fileName: ''
};
}
render() {
return (
<div>
<input id="file-input" type="file"></input>
<label
htmlFor="file-input"
id="fileinput-testclick"
onClick={() => {
document.getElementById('file-input').value = '';
document.getElementById('file-input').click();
}}
className="tran-button file-button">
{this.state.fileName ? 'Change File' : 'Choose File'}
</label>
</div>
);
}
}
export default SomeComponent;
index.spec.jsx
import React from 'react';
import SomeComponent from '.';
import { mount } from 'enzyme';
describe('SomeComponent', () => {
test('should call click event on File Input', () => {
document.getElementById = jest.fn();
const wrapper = mount(<SomeComponent></SomeComponent>);
expect(wrapper.find('label').text()).toBe('Choose File');
const input = wrapper.find('#file-input').getDOMNode();
const inputClickSpy = jest.spyOn(input, 'click');
document.getElementById.mockReturnValue(input);
wrapper.find('#fileinput-testclick').simulate('click');
expect(document.getElementById.mock.calls[0]).toEqual(['file-input']);
expect(document.getElementById.mock.calls[1]).toEqual(['file-input']);
expect(inputClickSpy).toBeCalledTimes(1);
expect(input.value).toBe('');
wrapper.setState({ fileName: 'UT.pdf' });
expect(wrapper.find('label').text()).toBe('Change File');
});
});
100%覆盖率的单元测试结果:
PASS src/stackoverflow/55011802/index.spec.jsx (9.277s)
SomeComponent
✓ should call click event on File Input (59ms)
-----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.jsx | 100 | 100 | 100 | 100 | |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 10.694s
源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/55011802
https://stackoverflow.com/questions/55011802
复制