`window` is not being exposed to Jest

后端 未结 6 1551
挽巷
挽巷 2021-02-12 16:50

I have a test that imports a component that in turn imports a helper file that uses the window object to pull out a query string parameter. I get the following erro

6条回答
  •  名媛妹妹
    2021-02-12 17:35

    You can simply mock location:

    global.location = {search: 'someSearchString'}
    

    Also note, that global in your test is the global context for the file to test (global === window)

    Note this will only work if your module make the window.location call after the test has been finishing import all the modules.

    export default () => window.location
    

    So if your module looks like this:

    const  l = window.location
    export default l 
    

    it will not work. In this case you could mock the module using jest.mock.

提交回复
热议问题