How to test window.location in Jest Redux
Answer a question
my redux action is changing window.location. Unfortunately my attempts have not worked.
I have a basic action that changes window.location. If I set a console log within the action, it's correct.
But when I console log the action within jest, it's not correct.
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'
....
};
Any tips or guidance would be greatly appreciated.
Answers
From the doc:
The top property on window is marked [Unforgeable] in the spec, meaning it is a non-configurable own property and thus cannot be overridden or shadowed by normal code running inside the jsdom, even using Object.defineProperty.
But, we can use Object.defineProperty() to define getter/setter for window.location with our own property _href. Besides, it seems you are using redux-thunk middleware, the loadScreen is an asynchronous action creator, you need to use await to wait for the completion of the asynchronous code.
E.g.
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',
}
package versions:
"jest": "^26.6.3",
test result:
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
更多推荐

所有评论(0)