如何使用Jest模拟HTML5 File对象

时间:2017-07-14 20:35:39

标签: javascript unit-testing jestjs flowtype

我有很多代码传递HTML 5文件对象。我为它编写了一套测试,然而,由于File对象上次修改日期,它打破了我的快照测试。

我试图模仿使用:

import traceback

def connect(self, host, port):
    try:
        telnet_obj = Telnet(host, port) # Use the constructor instead of the open() method.
    except Exception as e: # Should explicitly list exceptions to be caught. Also, only include the minimum code where you can handle the error.
        print("Connection cannot be established")
        traceback.print_exc() # Get a traceback of the error.
        # Do further error handling here and return/reraise.

    # This code is unrelated to opening a connection, so your error
    # handler for establishing a connection should not be run if
    # write() or read_until() raise an error.
    telnet_obj.write('AT'+"\r") # then use the returned object's methods.
    if telnet_obj.read_until("OK"):
        print("You are connected")

我收到错误,说找不到文件模块(我不需要在任何地方导入它...)

我还尝试扩展文件类并覆盖lastmodified get属性,它似乎没有修复我的快照。

处理此问题的最佳方式是什么?

1 个答案:

答案 0 :(得分:2)

您只需在全局命名空间中设置File

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