Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait for Redux Persist to rehydrate before ending test

I have the following code:

const App = () => {
    return (
        <Provider store={store}>
            <PersistGate persistor={persistor} loading={<Text>Loading!</Text>}>
                <ConnectedRootComponent />
            </PersistGate>
        </Provider>
    );
};

export default App;

which uses redux-persist to rehydrate state, and before this is complete, it will show what's sitting in the loading property. I have a Jest test (just the default one that comes with react native out of the box):

it('renders without crashing', () => {
  const rendered = renderer.create(<App />).toJSON();
  console.log("Rendering: " + JSON.stringify(rendered));
  expect(rendered).toBeTruthy();
});

but although the test passes I see that the actions that persist/PERSIST and persist/REHYDRATE are still occurring, and the value printed to the console in the test (the rendered output) is:

{
    "type": "Text",
    "props": {
        "accessible": true,
        "allowFontScaling": true,
        "ellipsizeMode": "tail"
    },
    "children": ["Loading!"]
}

What I want to do is wait until redux-persist has completed hydration, and then check the rendered value. How can I do this?

like image 885
user4184113 Avatar asked Jun 13 '18 04:06

user4184113


People also ask

What is rehydrate in redux persist?

It Persist and rehydrate a redux store. It means whenever user will come back to the app again from exit or from dead state, that user will get previous updated state within the app. ---------------------------------------------------------------------------------------------------------------------------

Does redux state persist on refresh?

With the Redux Persist library, developers can save the Redux store in persistent storage, for example, the local storage. Therefore, even after refreshing the browser, the site state will still be preserved.

What is persist rehydrate action?

The REHYDRATE action is dispatched by Redux Persist immediately after your persisted state is obtained from storage . If you return a new state object from the REHYDRATE action, this will be your finalized state.


Video Answer


1 Answers

import React from 'react';
import App, {persistor} from '../App';

import renderer from 'react-test-renderer';

it('renders without crashing', (done) => {
  const appRendered = renderer.create(<App />);
  persistor.subscribe(function(){
      const rendered = appRendered.toJSON();
      console.log("Rendering: " + JSON.stringify(rendered));
      expect(rendered).toBeTruthy();
      done();
  });
});

you just need to export the persistor from App file and then use the above code to test. it works perfectly, i have tested.

You can notice that persistor object can subscribe with a callback, which gets executed when the redux store has rehydrated.

like image 153
Inus Saha Avatar answered Oct 14 '22 13:10

Inus Saha