54 lines
1.3 KiB
TypeScript
54 lines
1.3 KiB
TypeScript
import assert from 'node:assert/strict';
|
|
import test from 'node:test';
|
|
|
|
import { saveWithOptimisticRollback } from './optimistic-persistence';
|
|
|
|
test('rolls back optimistic state when the save fails and state is unchanged', async () => {
|
|
const previous = [{ id: 'old' }];
|
|
const optimistic = [{ id: 'new' }];
|
|
let current = optimistic;
|
|
let rolledBack = false;
|
|
|
|
await assert.rejects(
|
|
() => saveWithOptimisticRollback({
|
|
save: async () => {
|
|
throw new Error('save failed');
|
|
},
|
|
expected: optimistic,
|
|
getCurrent: () => current,
|
|
rollback: () => {
|
|
rolledBack = true;
|
|
current = previous;
|
|
},
|
|
}),
|
|
/save failed/,
|
|
);
|
|
|
|
assert.equal(rolledBack, true);
|
|
assert.equal(current, previous);
|
|
});
|
|
|
|
test('does not roll back a newer optimistic state when an older save fails', async () => {
|
|
const optimistic = [{ id: 'new' }];
|
|
const newer = [{ id: 'newer' }];
|
|
let current = newer;
|
|
let rolledBack = false;
|
|
|
|
await assert.rejects(
|
|
() => saveWithOptimisticRollback({
|
|
save: async () => {
|
|
throw new Error('save failed');
|
|
},
|
|
expected: optimistic,
|
|
getCurrent: () => current,
|
|
rollback: () => {
|
|
rolledBack = true;
|
|
},
|
|
}),
|
|
/save failed/,
|
|
);
|
|
|
|
assert.equal(rolledBack, false);
|
|
assert.equal(current, newer);
|
|
});
|