diff --git a/test/fixtures.ts b/test/fixtures.ts index 1b110a1..5e7ad28 100644 --- a/test/fixtures.ts +++ b/test/fixtures.ts @@ -1,5 +1,7 @@ import { types } from 'mobx-state-tree' +import { ITransform, ITransformArgs } from '../src/index' + export const UserStoreF = types.model('UserStore', { name: 'John Doe', age: 32 @@ -13,3 +15,20 @@ export const persistedDataF = { name: 'Persisted Name', age: 35 } + +function changeName (name: string) { + let changeNameTransform: ITransformArgs + changeNameTransform = function (snapshot) { + snapshot.name = name + return snapshot + } + return changeNameTransform +} + +export function storeNameAsF (name: string): ITransform { + return {toStorage: changeName(name)} +} + +export function retrieveNameAsF (name: string): ITransform { + return {fromStorage: changeName(name)} +} diff --git a/test/index.spec.ts b/test/index.spec.ts index ac0561f..fb926be 100644 --- a/test/index.spec.ts +++ b/test/index.spec.ts @@ -2,13 +2,17 @@ import { getSnapshot } from 'mobx-state-tree' import { persist } from '../src/index' -import { UserStoreF, persistedDataF } from './fixtures' +import { UserStoreF, persistedDataF, storeNameAsF, retrieveNameAsF } from './fixtures' function getItem(key: string) { const item = window.localStorage.getItem(key) return item ? JSON.parse(item) : null // can only parse strings } +function setItem(key: string, value: object) { + return window.localStorage.setItem(key, JSON.stringify(value)) +} + describe('basic persist functionality', () => { beforeEach(() => window.localStorage.clear()) @@ -28,15 +32,16 @@ describe('basic persist functionality', () => { }) it('should load persisted data', async () => { - window.localStorage.setItem('user', JSON.stringify(persistedDataF)) + setItem('user', persistedDataF) const user = UserStoreF.create() await persist('user', user) + expect(getSnapshot(user)).toStrictEqual(persistedDataF) }) }) -describe('persist options', () => { +describe('basic persist options', () => { beforeEach(() => window.localStorage.clear()) it('shouldn\'t jsonify', async () => { @@ -74,3 +79,30 @@ describe('persist options', () => { expect(getItem('user')).toStrictEqual(snapshot) }) }) + +describe('transforms', () => { + beforeEach(() => window.localStorage.clear()) + + it('should apply toStorage transforms in order', async () => { + const user = UserStoreF.create() + await persist('user', user, { + transforms: [storeNameAsF('Jack'), storeNameAsF('Joe')] + }) + + user.changeName('Not Joe') // fire action to trigger onSnapshot + expect(getItem('user').name).toBe('Joe') + }) + + it('should apply fromStorage transforms in reverse order', async () => { + const persistedData = {...persistedDataF} + persistedData.name = 'Not Joe' + setItem('user', persistedData) + + const user = UserStoreF.create() + await persist('user', user, { + transforms: [retrieveNameAsF('Joe'), retrieveNameAsF('Jack')] + }) + + expect(getSnapshot(user).name).toBe('Joe') + }) +})