From 1323055253dc27f7c7567fe486b0c2e5909709c2 Mon Sep 17 00:00:00 2001 From: Eduardo San Martin Morote Date: Mon, 20 Jan 2020 17:50:35 +0100 Subject: [PATCH] test: getRootState --- __tests__/rootState.spec.ts | 48 +++++++++++++++++++++++++++++++++++++ src/store.ts | 15 ++++-------- 2 files changed, 53 insertions(+), 10 deletions(-) create mode 100644 __tests__/rootState.spec.ts diff --git a/__tests__/rootState.spec.ts b/__tests__/rootState.spec.ts new file mode 100644 index 00000000..ce3881dc --- /dev/null +++ b/__tests__/rootState.spec.ts @@ -0,0 +1,48 @@ +import { createStore, getRootState } from '../src' + +describe('Store', () => { + const useA = createStore({ + id: 'a', + state: () => ({ a: 'a' }), + }) + + const useB = createStore({ + id: 'b', + state: () => ({ b: 'b' }), + }) + + it('works with no stores', () => { + expect(getRootState({})).toEqual({}) + }) + + it('retrieves the root state of one store', () => { + const req = {} + useA(req) + expect(getRootState(req)).toEqual({ + a: { a: 'a' }, + }) + }) + + it('does not mix up different requests', () => { + const req1 = {} + const req2 = {} + useA(req1) + useB(req2) + expect(getRootState(req1)).toEqual({ + a: { a: 'a' }, + }) + expect(getRootState(req2)).toEqual({ + b: { b: 'b' }, + }) + }) + + it('can hold multiple stores', () => { + const req1 = {} + useA(req1) + useB(req1) + expect(getRootState(req1)).toEqual({ + a: { a: 'a' }, + b: { b: 'b' }, + }) + }) +}) diff --git a/src/store.ts b/src/store.ts index 0c1f5948..6db5db61 100644 --- a/src/store.ts +++ b/src/store.ts @@ -228,14 +228,11 @@ function setInitialState(store: Store): void { if (provider) provider.set(store) } -type StoreGetterWithGetters< - G extends Record> -> = { - [k in keyof G]: G[k] extends StoreGetter - ? (state: S, getters: G) => V - : never -} - +/** + * Gets the root state of all active stores. This is useful when reporting an application crash by + * retrieving the problematic state and send it to your error tracking service. + * @param req request key + */ export function getRootState(req: NonNullObject): Record { const stores = storesMap.get(req) if (!stores) return {} @@ -245,8 +242,6 @@ export function getRootState(req: NonNullObject): Record { rootState[store.id] = store.state } - console.log('global state', rootState) - return rootState } -- 2.47.2