React Jest测试文件上传时handler返回null的解决方法咨询
问题原因
- 你的
onUpload是异步函数,包含await异步逻辑,状态更新是异步执行的。你原测试是同步执行查询,此时文件读取、状态更新逻辑还未完成,values仍为空数组,自然查询不到handler元素 - 部分Jest+jsdom环境下,
Blob.text()原生方法实现存在兼容问题,不会正常返回文件内容
修复方案
1. 改造测试为异步逻辑 + 使用异步查询
userEvent.upload本身是异步方法,需要加await等待执行完成,同时使用异步查询方法findByTestId(内部自动封装了等待DOM更新的逻辑)代替同步的queryByTestId。
2. Mock Blob.text方法(可选,解决环境兼容问题)
如果确认是text()方法不生效,直接全局mock该方法返回你需要的JSON字符串即可。
完整修复后测试代码
import user from '@testing-library/user-event'; import someValues from '../somefile.json'; import { render } from '@testing-library/react'; // 全局mock Blob.text方法,直接返回目标json字符串,环境没问题的话可以删掉这行 jest.spyOn(Blob.prototype, 'text').mockResolvedValue(JSON.stringify(someValues)); // 测试用例改为async test('should pass', async () => { const { getByTestId, findByTestId } = 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'); // 等待upload操作执行完成 await user.upload(input, file); // 异步查询handler元素,最多等待默认的1000ms超时 const handler = await findByTestId('handler'); expect(handler).toBeTruthy(); });
内容的提问来源于stack exchange,提问作者AngularDebutant
相关产品推荐
相关产品推荐

