Skip to content

Commit

Permalink
Add a test for loaded state working correctly
Browse files Browse the repository at this point in the history
  • Loading branch information
jmeistrich committed Oct 24, 2023
1 parent 47e73a6 commit ca421f2
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions tests/persist.test.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,36 @@
import 'fake-indexeddb/auto';
import { transformOutData, persistObservable } from '../src/persist/persistObservable';
import { ObservablePersistLocalStorage } from '../src/persist-plugins/local-storage';
import { Change } from '../src/observableInterfaces';
import { observe } from '../src/observe';

Check warning on line 5 in tests/persist.test.ts

View workflow job for this annotation

GitHub Actions / Lint

'observe' is defined but never used
import { observable } from '../src/observable';
import { when } from '../src/when';

function promiseTimeout(time?: number) {
return new Promise((resolve) => setTimeout(resolve, time || 0));
}

class LocalStorageMock {
store: Record<any, any>;
constructor() {
this.store = {};
}
clear() {
this.store = {};
}
getItem(key: string) {
return this.store[key] || null;
}
setItem(key: string, value: any) {
this.store[key] = String(value);
}
removeItem(key: string) {
delete this.store[key];
}
}
// @ts-expect-error This is ok to do in jest
global.localStorage = new LocalStorageMock();

describe('Creating', () => {
test('Create with object', () => {
const obs$ = persistObservable(
Expand Down Expand Up @@ -41,6 +66,35 @@ describe('Creating', () => {
await promiseTimeout(10);
expect(setValue).toEqual('hello');
});
test('Loading state works correctly', async () => {
const nodes = observable<{ key: string }[]>([]);
let lastSet;
const { state } = persistObservable(nodes, {
pluginLocal: ObservablePersistLocalStorage,
pluginRemote: {
get: async () => {
const nodes = await new Promise<{ key: string }[]>((resolve) =>
setTimeout(() => resolve([{ key: 'key0' }]), 10),
);
return nodes.reduce(
(acc, node) => {
acc[node.key] = node;
return acc;
},
{} as Record<string, { key: string }>,
);
},
set: async ({ value }: { value: any; changes: Change[] }) => {
lastSet = value;
},
},
local: 'nodes',
});

await when(state.isLoadedLocal);
await when(state.isLoaded);
expect(lastSet).toEqual(undefined);
});
});

describe('Adjusting data', () => {
Expand Down

0 comments on commit ca421f2

Please sign in to comment.