Search code examples
javascriptunit-testingjestjsflowtype

How to mock the HTML5 File object with Jest


I have a lot of code passing around HTML 5 file objects. I wrote a suite of tests for it, however, it breaks my snapshot testing because of the File objects last modified date.

I attempted to mock using:

jest.mock('File', () => {
    return class MockFile {
        filename: string;

        constructor(parts: (string | Blob | ArrayBuffer | ArrayBufferView)[], filename: string, properties?: FilePropertyBag) {
            this.filename = filename;
        }
    }
});

I get errors saying the File module isn't found (I don't need to import it anywhere I use it...)

I also tried extending the file class and overriding the lastmodified get property, and it didn't seem to fix my snapshots.

What's the best way to handle this?


Solution

  • You just need to set File in the global namespace:

    global.File = class MockFile {
        filename: string;
        constructor(parts: (string | Blob | ArrayBuffer | ArrayBufferView)[], filename: string, properties ? : FilePropertyBag) {
          this.filename = filename;
        }
      }