reactjs - 如何在 Jest Redux 中测试 window.location
问题描述
我的 redux 操作正在更改 window.location。不幸的是,我的尝试没有奏效。
我有一个更改 window.location 的基本操作。如果我在操作中设置控制台日志,那是正确的。
但是,当我在控制台中记录该操作时,这是不正确的。
screenActions.test.js
store.dispatch(actions.loadScreen())
console.log(window.location) // does not produce a string, rather the location object
screen.actions.js
export const loadScreen = () => async (dispatch, getState) => {
....
window.location = 'www.google.com';
console.log(window.location) // produces 'www.google.com'
....
};
任何提示或指导将不胜感激。
解决方案
从文档:
window 上的 top 属性在规范中被标记为 [Unforgeable],这意味着它是一个不可配置的自己的属性,因此即使使用 Object.defineProperty,也不能被 jsdom 内运行的普通代码覆盖或隐藏。
但是,我们可以使用我们自己的属性Object.defineProperty()
来定义 getter/setter 。另外,你好像在使用中间件,是一个异步动作创建器,你需要用它来等待异步代码的完成。window.location
_href
redux-thunk
loadScreen
await
例如
screen.actions.js
:
export const loadScreen = () => async (dispatch, getState) => {
window.location = 'www.google.com';
console.log(window.location);
};
screen.actions.test.js
:
import configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import * as actions from './screen.actions';
const mws = [thunk];
const mockStore = configureStore(mws);
describe('67339402', () => {
it('should pass', async () => {
Object.defineProperty(window, 'location', {
set(val) {
this._href = val;
},
get() {
return this._href;
},
});
const store = mockStore({});
await store.dispatch(actions.loadScreen());
expect(window.location).toEqual('www.google.com');
console.log(window.location.href); // top property on window is Unforgeable
});
});
jest.config.js
:
module.exports = {
preset: 'ts-jest/presets/js-with-ts',
testEnvironment: 'jsdom',
}
包版本:
"jest": "^26.6.3",
测试结果:
PASS examples/67339402/screen.actions.test.js (10.31 s)
67339402
✓ should pass (19 ms)
console.log
www.google.com
at examples/67339402/screen.actions.js:3:11
console.log
undefined
at examples/67339402/screen.actions.test.js:21:13
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 11.698 s
推荐阅读
- python - 多列pandas df上的除法
- java - Java Android 简单重构
- c++ - 避免使用 std::any 编写相同的重复类型检查代码
- java - Spring 的 SwitchUserFilter 线程安全吗?
- sql - Mad cursor (SQL Server) 使程序冻结和崩溃
- reactjs - React Router 使用 /:username 或 /component/ 渲染组件
- gradle - 从 Procfile 调用 Gradlew
- excel - 如何将 Excel 列名转换为数字,反之亦然?
- javascript - 迭代对象数组属性的值
- azure - Azure 映射过度命中