最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to mock the HTML5 File object with Jest - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question edited Jul 14, 2017 at 21:33 Andreas Köberle 111k58 gold badges280 silver badges307 bronze badges asked Jul 14, 2017 at 20:35 TheTFoTheTFo 8112 gold badges10 silver badges25 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

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

Another way to solve it is using jest.fn from jest mocking the returned value of File

global.File = jest.fn((file, fileName) => ({
  name: fileName,
  type: fileName.split('.')[1]
}))
发布评论

评论列表(0)

  1. 暂无评论