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);
});
减速器应该是纯功能的。这就是为什么你测试它有问题。来自Docs。 “给出相同的参数,它应该计算下一个状态并返回它,没有意外,没有副作用,没有API调用,没有突变,只是一个计算” –
修改DOM的逻辑位于何处? – Complexity
那么,有选择。例如中间件或动作创建者。但绝对不是减速器,因为制造减速器不是纯粹的遗址可测试性,可复制性等。 –