在反应笑话中测试文件上传

Test file upload in react jest

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

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

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

主要怀疑这条线不是在开玩笑。还是我处理不当

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

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

您需要模拟 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