Mocking globals in Jest

后端 未结 5 1491
梦谈多话
梦谈多话 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:35

    The correct way of doing this is to use spyOn. The other answers here, even though they work, don't consider cleanup and pollute the global scope.

    // beforeAll
    jest
      .spyOn(window, 'navigator', 'get')
      .mockImplementation(() => { ... })
    
    // afterAll
    jest.restoreAllMocks();
    

提交回复
热议问题