javascript - 在 react Jest 中测试文件上传

标签 javascript reactjs jestjs react-hooks react-testing-library

我有这样的代码(只保留相关代码)

function App() {
  const [values, setValues] = useState([]);

  async function onUpload(event) {
    if (event?.target.files?.length) {
      const data = await event.target.files[0].text();
      const json = JSON.parse(data);
      setValues(json);
    } else {
      throw new Error('couldnt get files');
    }
  }

  return (
    <div>
      {Boolean(!values.length) && (
        <input data-testid="upInput" accept="application/JSON" type="file" onChange={onUpload} />
      )}
      {Boolean(values.length) && (
        <div data-testid="handler">
          <ValuesHandler values={values} />
        </div>
      )}
    </div>
  );
}

现在我想测试当用户上传文件时 values 是否设置正确,然后 ValuesHandler 是否出现在页面中。

我正在我的 App.test.tsx 中朝这个方向尝试

import user from '@testing-library/user-event';
import someValues from '../somefile.json';
import { render } from '@testing-library/react';

test('should pass', () => {
    const { getByTestId, queryByTestId } = render(<App />);
    const str = JSON.stringify(someValues);
    const blob = new Blob([str]);
    const file = new File([blob], 'values.json', {
        type: 'application/JSON',
    });
    const input = getByTestId('upInput');

    user.upload(input, file);

    const handler = queryByTestId('handler');

    expect(handler).toBeTruthy();
});

由于处理程序为空而失败。

主要怀疑是这条线不是在开 Jest 。或者我处理不当。

    const data = await event.target.files[0].text();

我正在考虑模拟 Blob.text 方法以直接返回文件的内容。但不确定如何。

最佳答案

您需要模拟 File.text() 方法。只需将模拟的 .text() 方法添加到 File.prototype

例如

App.tsx:

import React, { useState } from 'react';

export function App() {
  const [values, setValues] = useState([]);

  async function onUpload(event) {
    if (event?.target.files?.length) {
      const data = await event.target.files[0].text();
      const json = JSON.parse(data);
      setValues(json);
    } else {
      throw new Error('couldnt get files');
    }
  }

  return (
    <div>
      {Boolean(!values.length) && (
        <input data-testid="upInput" accept="application/JSON" type="file" onChange={onUpload} />
      )}
      {Boolean(values.length) && <div data-testid="handler">ValuesHandler</div>}
    </div>
  );
}

App.test.tsx:

import React from 'react';
import user from '@testing-library/user-event';
import { render, waitFor } from '@testing-library/react';
import { App } from './App';

const someValues = [{ name: 'teresa teng' }];

describe('68452480', () => {
  test('should pass', async () => {
    const { getByTestId, queryByTestId } = render(<App />);
    const str = JSON.stringify(someValues);
    const blob = new Blob([str]);
    const file = new File([blob], 'values.json', {
      type: 'application/JSON',
    });
    File.prototype.text = jest.fn().mockResolvedValueOnce(str);
    const input = getByTestId('upInput');
    user.upload(input, file);
    await waitFor(() => expect(queryByTestId('handler')).toBeTruthy());
  });
});

测试结果:

 PASS  examples/68452480/App.test.tsx (9.968 s)
  68452480
    ✓ should pass (53 ms)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
----------|---------|----------|---------|---------|-------------------
All files |   88.89 |    78.57 |     100 |   88.89 |                   
 App.tsx  |   88.89 |    78.57 |     100 |   88.89 | 12                
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        10.694 s

关于javascript - 在 react Jest 中测试文件上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68452480/

相关文章:

javascript - 在 React 中使用 Jest 测试函数的返回值

javascript - Node Jest 在函数中模拟函数

javascript - toggle() 函数无需传递第二个参数即可工作。

node.js - 如何在 443 端口上配置多个进程? Apache - ubuntu

reactjs - 模拟点击 enzyme

javascript - 检查数组中是否存在字符串值并返回找到的数组值 js

javascript - 如何为 react/redux 创建加载器旋转

javascript - Chrome JavaScript CPU 分析器做了什么可能会影响程序的性能(在分析期间)?

javascript - jstree中如何获取被点击的对象

javascript - 如何使用 Jest 测试是否使用定义的参数( toHaveBeenCalledWith )调用了函数