Search code examples
reactjstestingjestjsreact-testing-library

How to use File.text() in jest?


I have some problems to make some tests pass. After a few hours lost trying to figure out what is going on, I have realized that jest has some problem with Files

I have wrote a simple test, to expect over a file content:

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

That simple code, work when is executed in the real aplication within a browser. However, when I launch the test suite, I just get an error:

TypeError: file.text is not a function

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

So, what I need to jest can work with Files?


Solution

  • Finally I found a workaround thanks to @EstusFlask comments.

    I have mocked File.prototype.text to return the file object itself. Then I can read its content on test with a FileReader.