I am attempting to test a specific route within my React component that relies on the window having visible search parameters. For example:
const MyComponent = () => {
if (window.location.search) {
return <h1 data-testid="query">Has search params</h1>
}
return <h1 data-testid="no-query">No search params</h1>
}
My test for such an occurance is as such:
it('should go down query route', () => {
const initialState = configState(); // Set up Redux store
const path = '/my-comp';
const search = '?some=search';
const history = createMemoryHistory({
initialEntries: [{
pathname: path,
search: search
}]
});
history.push(redirectFrom);
const mockStore = configureStore();
const {queryByTestId} = render (
<Provider store={mockStore(state)}>
<Router history={history}>
<MyComponent />
</Router>
</Provider>
);
expect(queryByTestId('query')).not.toBeNull();
expect(queryByTestId('query').textContent).toBe('Has search params');
expect(queryByTestId('no-query')).toBeNull();
});
I found that the tests weren't passing, so I added a console.log(window.location)
at the start of my component to see the path
, search
etc that the component was being rendered with and I found that all of the expected properties were missing:
{
href: 'http://localhost/',
origin: 'http://localhost',
host: 'localhost',
hostname: 'localhost',
port: '',
pathname: '/',
search: '',
hash: ''
}
A bit of background info:
- The App is built with Redux
- This component is rendered as part of a
<Router>
within an App as you might expect:
const App = () => {
return (
<Provider>
<ConnectedRouter>
<Route path="my-comp" component={MyComponent} />
// More routes here
</ConnectedRouter>
</Provider>
)
}
Aucun commentaire:
Enregistrer un commentaire