|
| 1 | +// @flow |
| 2 | + |
| 3 | +import test from 'ava' |
| 4 | +import sinon from 'sinon' |
| 5 | + |
| 6 | +import _ from 'lodash' |
| 7 | +import configureStore from 'redux-mock-store' |
| 8 | +import { createStore } from 'redux' |
| 9 | + |
| 10 | +import getStoredState from '../src/getStoredState' |
| 11 | +import persistReducer from '../src/persistReducer' |
| 12 | +import persistStore from '../src/persistStore' |
| 13 | +import { createMemoryStorage } from 'storage-memory' |
| 14 | +import { PERSIST, REHYDRATE, FLUSH } from '../src/constants' |
| 15 | +import sleep from './utils/sleep' |
| 16 | + |
| 17 | +const initialState = { a: 0 } |
| 18 | +const persistObj = { |
| 19 | + version: 1, |
| 20 | + rehydrated: true |
| 21 | +}; |
| 22 | + |
| 23 | +let reducer = (state = initialState, { type }) => { |
| 24 | + console.log('action', type) |
| 25 | + if (type === 'INCREMENT') { |
| 26 | + return _.mapValues(state, v => v + 1) |
| 27 | + } |
| 28 | + return state |
| 29 | +} |
| 30 | + |
| 31 | +const memoryStorage = createMemoryStorage() |
| 32 | + |
| 33 | +const config = { |
| 34 | + key: 'resync-reducer-test', |
| 35 | + version: 1, |
| 36 | + storage: memoryStorage, |
| 37 | + debug: true, |
| 38 | + throttle: 1000, |
| 39 | +} |
| 40 | + |
| 41 | +test('state is resync from storage', t => { |
| 42 | + return new Promise((resolve, reject) => { |
| 43 | + let rootReducer = persistReducer(config, reducer) |
| 44 | + const store = createStore(rootReducer) |
| 45 | + |
| 46 | + const persistor = persistStore(store, {}, async () => { |
| 47 | + |
| 48 | + // 1) Make sure redux-persist and storage are in the same state |
| 49 | + |
| 50 | + await persistor.flush(); |
| 51 | + let storagePreModify = await getStoredState(config) |
| 52 | + |
| 53 | + const oldStorageState = { |
| 54 | + ...initialState, |
| 55 | + _persist: persistObj, |
| 56 | + }; |
| 57 | + t.deepEqual( |
| 58 | + storagePreModify, |
| 59 | + oldStorageState |
| 60 | + ) |
| 61 | + |
| 62 | + // 2) Change the storage directly (so redux-persist won't notice it changed) |
| 63 | + |
| 64 | + const newStorageValue = { |
| 65 | + a: 1, // override the value of a |
| 66 | + _persist: JSON.stringify(persistObj), |
| 67 | + } |
| 68 | + await memoryStorage.setItem(`persist:${config.key}`, JSON.stringify(newStorageValue)); |
| 69 | + let storagePostModify = await getStoredState(config) |
| 70 | + |
| 71 | + // 3) Call resync and make sure redux-persist state was overriden by storage content |
| 72 | + |
| 73 | + await persistor.resync(); |
| 74 | + t.deepEqual( |
| 75 | + storagePostModify, |
| 76 | + { |
| 77 | + a: 1, |
| 78 | + _persist: persistObj, |
| 79 | + } |
| 80 | + ) |
| 81 | + |
| 82 | + resolve() |
| 83 | + }) |
| 84 | + }) |
| 85 | +}) |
0 commit comments