我的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'
....
};
如有任何提示或指导,我们将不胜感激。
来自文档:
窗口上的顶部属性在规范中标记为〔Unforgeable〕,这意味着它是一个不可配置的自己的属性,因此即使使用Object.defineProperty,也不能被jsdom内运行的正常代码覆盖或隐藏。
但是,我们可以使用Object.defineProperty()
为具有自己的属性_href
的window.location
定义getter/setter。此外,您似乎使用的是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