Mocking globals in Jest

后端 未结 5 1463
梦谈多话
梦谈多话 2020-11-28 13:21

Is there any way in Jest to mock global objects, such as navigator, or Image*? I\'ve pretty much given up on this, and left it up to a series of mo

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-28 13:48

    As every test suite run its own environment, you can mock globals by just overwriting them. All global variables can be accessed by the global namespace:

    global.navigator = {
      onLine: true
    }
    

    The overwrite has only effects in your current test and will not effect others. This also a good way to handle Math.random or Date.now.

    Note, that through some changes in jsdom it could be possible that you have to mock globals like this:

    Object.defineProperty(globalObject, key, { value, writable: true });
    

提交回复
热议问题