Реакция хуков не устанавливает состояние при тестировании с использованием Jest - PullRequest
0 голосов
/ 11 ноября 2019

У меня есть компонент реагирования

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);
  });
}

Новывод всегда "файл не выбран". Любая помощь будет оценена.

1 Ответ

1 голос
/ 11 ноября 2019

Ваш код отлично работает для меня.

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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...