试图通过以下单击事件,但不确定如何在document.getElementById('file-input')。value上调用onclick 将Jest和Enzyme用于React JS
这是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>
答案 0 :(得分:0)
这是单元测试解决方案:
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