Ваш код отлично работает для меня.
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