首页 > 解决方案 > 如何在玩笑中使用 File.text()?

问题描述

我有一些问题要通过一些测试。经过几个小时试图弄清楚发生了什么,我意识到 jest 有一些问题Files

我写了一个简单的测试,期望超过一个文件内容:

describe(".file test", () => {
    test("jest can work whit files", async () => {
      const aContent = "a_content";      
      const file = new File([aContent], "aFile.txt");
      const fileContent = await file.text()
      expect(fileContent).toBe(aContent)
    })
 )

那个简单的代码,在浏览器中的真实应用程序中执行时工作。但是,当我启动测试套件时,我得到一个错误:

类型错误:file.text 不是函数

  30 |       const aContent = "a_content";
  31 |       const file = new File([aContent], "aFile.txt");
> 32 |       const fileContent = await file.text()
     |                                      ^
  33 |       expect(fileContent).toBe(aContent)

那么,我需要开玩笑的东西可以与文件一起使用吗?

标签: reactjstestingjestjsreact-testing-library

解决方案


最后,感谢@EstusFlask 的评论,我找到了一种解决方法。

我嘲笑File.prototype.text返回文件对象本身。然后我可以用FileReader.


推荐阅读