来自doc:
window 上的 top 属性在规范中被标记为 [Unforgeable],这意味着它是一个不可配置的自有属性,因此即使使用 Object.defineProperty,也不能被 jsdom 内运行的正常代码覆盖或隐藏。
但是,我们可以使用Object.defineProperty() 为window.location 定义getter/setter,并使用我们自己的属性_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