2017-04-24 490 views
0

我正在寫一個SPA(React)應用程序,我正在使用Redux和Jest作爲應用程序。 現在,在我的reducer中,我確實有一個操作,在加載所有內容後,會從屏幕中刪除一些初始HTML(閃屏)。這與window.onload()事件進行覈對。如何使用JEST測試瀏覽器窗口行爲?

不管怎麼說,當我用JEST調用這個時,會拋出一個錯誤,說window.onload不是函數。

這怎麼解決,下面是我的減速機。

export const reduxReducer = (state = initialReducerState, action) => { 
     switch (action.type) { 
      case ReduxActions.FADE_OUT_AND_REMOVE_SPLASH_SCREEN: 
       // Set an event handler to remove the splash screen after the window has been laoded. 
       // This ensures that all the content is loaded. 
       window.onload(() => { 
        document.getElementsByClassName("splash-screen")[0].classList.add("fade-out"); 

        // Set a timeout to remove the splash screen from the DOM as soon as the animation is faded. 
        setTimeout(() => { 
         let splashScreenElement = document.getElementsByClassName("splash-screen")[0]; 
         splashScreenElement.parentNode.removeChild(splashScreenElement); 

         let styleElements = document.getElementsByTagName('style'); 
         for (let i = 0; i < styleElements.length; i++) { 
          styleElements[i].parentNode.removeChild(styleElements[i]); 
         } 
        }, 500); 
       }); 



      // Returns the updated state. 
      return { 
       ...state, 
       appBootstrapped: false 
      } 
     default: 
      return { 
       ...state 
      }; 
    } 
}; 

和關閉過程我的測試文件:

it("Update 'appBootstrapped' to true when the 'FADE_OUT_AND_REMOVE_SPLASH_SCREEN' action is invoked.",() => { 
    // Arrange. 
    const expectedReduxState = { 
     appBootstrapped: true 
    }; 

    // Assert. 
    expect(reduxReducer(undefined, { type: FADE_OUT_AND_REMOVE_SPLASH_SCREEN })).toEqual(expectedReduxState); 
}); 
+0

減速器應該是純功能的。這就是爲什麼你測試它有問題。來自Docs。 「給出相同的參數,它應該計算下一個狀態並返回它,沒有意外,沒有副作用,沒有API調用,沒有突變,只是一個計算」 –

+0

修改DOM的邏輯位於何處? – Complexity

+0

那麼,有選擇。例如中間件或動作創建者。但絕對不是減速器,因爲製造減速器不是純粹的遺址可測試性,可複製性等。 –

回答

0

您可以設置window.onload到任何你想要的。所以最簡單的就是把它設置爲這樣偵測:

global.onload = jest.fn()