我有一个反应组件
const Upload = (props) => {
const [fileName, setFileName] = useState("no file chosen")
function handleFile(e) {
const [sFile] = e.target.files;
setFileName(sFile.name);
}
const chooseFile = (
<label>
<input id="file-upload" type="file" accept=".pdf, application/pdf" onChange={handleFile} />
choose_file
</label>
<label className='file-text'>
{fileName}
</label>
);
return (
<React.Fragment>
{chooseFile}
</React.Fragment>
);
};
我有这个测试来检查状态fileName的值更改,以便它显示所选文件的名称
beforeEach(() => {
wrapper = shallow(<Upload />);
});
describe('Choose File', () => {
const mockedFile = 'application.pdf';
const event = {
target: {
files: [{ name: 'application.pdf' }]
}
};
it('displays the file name when a file is selected', () => {
wrapper.find('#file-upload').simulate('change', event);
wrapper.update();
expect(wrapper.find('label').at(1).text()).toEqual(mockedFile);
});
}
但是输出总是"未选择任何文件"。如有任何帮助,我们将不胜感激。
您的代码对我来说很好。
index.tsx
:
import React, { useState } from 'react';
export const Upload = props => {
const [fileName, setFileName] = useState('no file chosen');
function handleFile(e) {
const [sFile] = e.target.files;
setFileName(sFile.name);
}
return (
<React.Fragment>
<label>
<input id="file-upload" type="file" accept=".pdf, application/pdf" onChange={handleFile} />
choose_file
</label>
<label className="file-text">{fileName}</label>
</React.Fragment>
);
};
index.spec.tsx
:
import React from 'react';
import { shallow } from 'enzyme';
import { Upload } from './';
let wrapper;
beforeEach(() => {
wrapper = shallow(<Upload />);
});
describe('Choose File', () => {
const mockedFile = 'application.pdf';
const event = {
target: {
files: [{ name: 'application.pdf' }]
}
};
it('displays the file name when a file is selected', () => {
wrapper.find('#file-upload').simulate('change', event);
wrapper.update();
expect(
wrapper
.find('label')
.at(1)
.text()
).toEqual(mockedFile);
});
});
100%覆盖率的单元测试结果:
PASS src/stackoverflow/58793061/index.spec.tsx
Choose File
✓ displays the file name when a file is selected (12ms)
-----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
-----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.tsx | 100 | 100 | 100 | 100 | |
-----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 3.924s
依赖关系版本:
"enzyme": "^3.10.0",
"enzyme-adapter-react-16": "^1.15.1",
"jest": "^24.9.0",
"jest-environment-enzyme": "^7.1.1",
"jest-enzyme": "^7.1.1",
"react": "^16.11.0",
源代码:https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/58793061