如何在react中为拖放文件编写jest测试用例?

vbopmzt1  于 2023-08-01  发布在  Jest
关注(0)|答案(1)|浏览(147)

我是写测试用例的新手,尝试在react中上传文件时编写拖放事件。我已经通过几个链接,但仍然无法找到任何答案,它使用正常的React测试库。
代码如下:

<div
        className={`dropzone ${isDragging ? "dragging" : ""}`}
        onDragEnter={handleDragEnter}
        onDragLeave={handleDragLeave}
        onDragOver={handleDragOver}
        onDrop={handleDrop}
      >
        <input
          type="file"
          id="input-file-upload"
          className="inputFile"
          data-testid="input-field"
          onChange={handleFileInputChange}
        />
        <label htmlFor="input-file-upload" id="label-file-upload">
          <div>
            <button
              style={{ display: "block", margin: "auto" }}
              onClick={handleButtonClick}
            >
              Add File
            </button>
            {selectedFile ? (
              <p>Selected File: {selectedFile.name}</p>
            ) : (
              <p>Drag and drop files</p>
            )}
          </div>
        </label>
      </div>

字符串
以下是dragEnter、dragOver和dragLeave事件:

const handleDragEnter = (e) => {
    e.preventDefault();
    setIsDragging(true);
  };

  const handleDragLeave = (e) => {
    e.preventDefault();
    setIsDragging(false);
  };

  const handleDragOver = (e) => {
    e.preventDefault();
  };

  const handleDrop = (e) => {
    e.preventDefault();
    setIsDragging(false);

    const file = e.dataTransfer.files[0];
    setSelectedFile(file);
    console.log(file);
  };


下面是整个代码:(https://codesandbox.io/s/upbeat-glade-x9h48c?file=/src/index.js)有人能在拖放测试用例中帮助我吗?提前感谢!

ccrfmcuu

ccrfmcuu1#

您可以使用fireEvent[eventName]的RTL包。
dataTransfer:拖动事件具有dataTransfer属性,该属性包含操作期间传输的数据。为了方便起见,如果在eventProperties(第二个参数)中提供dataTransfer属性,则这些属性将添加到事件中。
使用fireEvent.drop()触发onDrop事件处理程序。
例如:
index.jsx

import React, { useState } from 'react';

export function App() {
    const [isDragging, setIsDragging] = useState(false);
    const [selectedFile, setSelectedFile] = useState(null);

    const handleDragEnter = (e) => {
        e.preventDefault();
        setIsDragging(true);
    };

    const handleDragLeave = (e) => {
        e.preventDefault();
        setIsDragging(false);
    };

    const handleDragOver = (e) => {
        e.preventDefault();
    };

    const handleDrop = (e) => {
        e.preventDefault();
        setIsDragging(false);
        const file = e.dataTransfer.files[0];
        setSelectedFile(file);
        console.log(file);
    };

    const handleFileInputChange = (e) => {
        const file = e.target.files[0];
        setSelectedFile(file);
        console.log(file);
    };

    return (
        <div
            className={`dropzone ${isDragging ? 'dragging' : ''}`}
            data-testid='dropzone'
            onDragEnter={handleDragEnter}
            onDragLeave={handleDragLeave}
            onDragOver={handleDragOver}
            onDrop={handleDrop}
        >
            <input
                type='file'
                id='input-file-upload'
                className='inputFile'
                data-testid='input-field'
                onChange={handleFileInputChange}
            />
            <label htmlFor='input-file-upload' id='label-file-upload'>
                <div>{selectedFile ? <p>Selected File: {selectedFile.name}</p> : <p>Drag and drop files</p>}</div>
            </label>
        </div>
    );
}

字符串
index.test.jsx

import '@testing-library/jest-dom';
import { fireEvent, render, screen } from '@testing-library/react';
import React from 'react';
import { App } from '.';

test.only('input field onChange', () => {
    render(<App />);
    const dropzone = screen.getByTestId('dropzone');
    expect(screen.getByText('Drag and drop files')).toBeInTheDocument();
    fireEvent.drop(dropzone, { dataTransfer: { files: [new File(['hello'], 'hello.png', { type: 'image/png' })] } });
    expect(screen.getByText('Selected File: hello.png')).toBeInTheDocument();
});


试验结果:

PASS  stackoverflow/76759517/index.test.tsx (8.908 s)
  ✓ input field onChange (43 ms)

  console.log
    File {}

      at handleDrop (stackoverflow/76759517/index.jsx:26:11)

-----------|---------|----------|---------|---------|--------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s  
-----------|---------|----------|---------|---------|--------------------
All files  |   65.22 |       75 |   33.33 |   65.22 |                    
 index.jsx |   65.22 |       75 |   33.33 |   65.22 | 8-9,13-14,18,30-32 
-----------|---------|----------|---------|---------|--------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        9.217 s


软件包版本:

"@testing-library/react": "^11.2.7",
"@testing-library/user-event": "^14.4.3",
"@testing-library/jest-dom": "^5.16.5",
"jest": "^26.6.3",
"react": "^16.14.0",
"react-dom": "^16.14.0",

相关问题