How to access history object in Jest
I have an if condition that looks like this:
if (history.state !== null && history.state.query)
The problem is, although it doesn't work in Jest, as it history
is an empty object in my tests.
What do I need to do in my tests to use the object history
? I am running this with React on a Node.js server. Not sure if this matters, but I'm using React Router as well.
Test case:
beforeEach(() => {
window.ga = jest.fn();
window.analytics = jest.fn();
window.analytics.track = jest.fn();
});
it('should set up props from history state', () => {
let location = {
pathname: '/explore',
query: {
query: 'yahoo',
},
};
global.history = { state: { query: 'google'} };
const wrapper = mount(
<LandingPage location={location} />
);
console.log("global.history.state: " + global.history.state); // prints null
});
Part of a component (cannot fit the whole component):
if (props.location && props.location.pathname === '/explore') {
explorePath = true;
skipIntro = true;
explore = true;
/* checks if history.state is not equal to null
* if check passes, search query and results will appear
*/
if (history.state !== null && history.state.query) {
currentValue = history.state.query;
employeeMin = history.state.eMin;
employeeMax = history.state.eMax;
revenueMin = history.state.rMin;
revenueMax = history.state.rMax;
}
} else {
explore = skipIntro;
}
source to share
You need to use createMemoryStore
so createMemoryStore
history
as follows:
import React from 'react'
import { shallow } from 'enzyme'
import { createMemoryHistory } from 'history'
import Page from '../Page'
describe('<Page />', () => {
it('should render correctly', () => {
const history = createMemoryHistory('/dashboard')
const renderedComponent = shallow(
<Page history={history} />
)
expect(renderedComponent).toMatchSnapshot()
})
})
Recommendations:
source to share
My way of solving this problem is to emulate the history API completely, because JSDom doesn't support the history API either. There is a part of my JSDomTestWrapper class and it is very special to my project, although you can steal some ideas :)
https://gist.github.com/studentIvan/3d342cc555644ca9448cbbafcffbc9cf#file-jsdom-wrapper-js-L69
source to share