Mocking globals in Jest

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

    If you are using react-testing-library and you use the cleanup method provided by the library, it will remove all global declarations made in that file once all tests in the file have run. This will then not carry over to any other tests run.

    Example:

    import { cleanup } from 'react-testing-library'
    
    afterEach(cleanup)
    
    global.getSelection = () => {
    
    }
    
    describe('test', () => {
      expect(true).toBeTruthy()
    })
    

提交回复
热议问题