|
1 | 1 | /// <reference types="@types/jest" />
|
| 2 | +import { getSnapshot } from 'mobx-state-tree' |
2 | 3 |
|
3 | 4 | import { persist } from '../src/index'
|
4 | 5 | import { UserStore } from './fixtures'
|
5 | 6 |
|
6 |
| -describe('initialization', () => { |
| 7 | +function getItem(key: string) { |
| 8 | + const item = window.localStorage.getItem(key) |
| 9 | + return item ? JSON.parse(item) : null // can only parse strings |
| 10 | +} |
| 11 | + |
| 12 | +describe('basic persist options', () => { |
7 | 13 | beforeEach(() => window.localStorage.clear())
|
8 | 14 |
|
9 | 15 | it('should persist nothing if no actions are used', async () => {
|
10 | 16 | const user = UserStore.create()
|
11 | 17 | await persist('user', user)
|
12 | 18 |
|
13 |
| - expect(window.localStorage.getItem('user')).toBe(null) |
| 19 | + expect(getItem('user')).toBe(null) |
| 20 | + }) |
| 21 | + |
| 22 | + it('should persist snapshot when action used', async () => { |
| 23 | + const user = UserStore.create() |
| 24 | + await persist('user', user) |
| 25 | + |
| 26 | + user.changeName('Joe') // fire action to trigger onSnapshot |
| 27 | + expect(getItem('user')).toStrictEqual(getSnapshot(user)) |
| 28 | + }) |
| 29 | + |
| 30 | + it('should whitelist', async () => { |
| 31 | + const user = UserStore.create() |
| 32 | + await persist('user', user, { |
| 33 | + whitelist: ['name'] |
| 34 | + }) |
| 35 | + |
| 36 | + user.changeName('Joe') // fire action to trigger onSnapshot |
| 37 | + const snapshot = { ...getSnapshot(user) } // need to shallow clone as otherwise properties are non-configurable (https://github.com/agilgur5/mst-persist/pull/21#discussion_r348105595) |
| 38 | + delete snapshot['age'] |
| 39 | + expect(getItem('user')).toStrictEqual(snapshot) |
| 40 | + }) |
| 41 | + |
| 42 | + it('should blacklist', async () => { |
| 43 | + const user = UserStore.create() |
| 44 | + await persist('user', user, { |
| 45 | + blacklist: ['age'] |
| 46 | + }) |
| 47 | + |
| 48 | + user.changeName('Joe') // fire action to trigger onSnapshot |
| 49 | + const snapshot = { ...getSnapshot(user) } // need to shallow clone as otherwise properties are non-configurable (https://github.com/agilgur5/mst-persist/pull/21#discussion_r348105595) |
| 50 | + delete snapshot['age'] |
| 51 | + expect(getItem('user')).toStrictEqual(snapshot) |
14 | 52 | })
|
15 | 53 | })
|
0 commit comments