Skip to content

Commit

Permalink
fix(testing): prevent first computed reading of mocked atom #995
Browse files Browse the repository at this point in the history
  • Loading branch information
artalar committed Dec 30, 2024
1 parent a81e9a3 commit 5231d20
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 18 deletions.
12 changes: 12 additions & 0 deletions packages/testing/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,4 +62,16 @@ test('mockAction', () => {
;`👍` //?
})

test('mock computed atom', () => {
const testAtom = atom<string>(() => {
throw new Error('unreachable')
}, 'testAtom')

const ctx = createTestCtx()

ctx.mock(testAtom, 'mocked')

assert.is(ctx.get(testAtom), 'mocked')
})

test.run()
25 changes: 7 additions & 18 deletions packages/testing/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,7 @@ import {
} from '@reatom/core'
import { createMemStorage } from '@reatom/persist'

export function mockFn<I extends any[], O>(
fn: (...input: I) => O = (...i: any) => void 0 as any,
) {
export function mockFn<I extends any[], O>(fn: (...input: I) => O = (...i: any) => void 0 as any) {
const _fn = Object.assign(
function (...i: I) {
try {
Expand Down Expand Up @@ -60,10 +58,7 @@ export const getDuration = async (cb: () => void) => {
export interface TestCtx extends Ctx {
mock<T>(anAtom: Atom<T>, fallback: T): Unsubscribe

mockAction<I extends any[], O>(
anAction: Action<I, O>,
cb: Fn<[Ctx, ...I], O>,
): Unsubscribe
mockAction<I extends any[], O>(anAction: Action<I, O>, cb: Fn<[Ctx, ...I], O>): Unsubscribe

subscribeTrack<T, F extends Fn<[T]>>(
anAtom: Atom<T>,
Expand Down Expand Up @@ -134,27 +129,22 @@ export const createTestCtx = (options?: CtxOptions): TestCtx => {
},
mock<T>(anAtom: Atom<T>, fallback: T) {
const proto = anAtom.__reatom
let read: Fn
const { computer } = proto
proto.computer = null

get((_read, actualize) => {
read = _read
actualize!(ctx, proto, (patchCtx: Ctx, patch: AtomCache) => {
patch.state = fallback
// disable computer
patch.pubs = [ctx.cause]
})
mocks.set(proto, fallback)
})

return () => {
read(proto).pubs = []
proto.computer = computer
mocks.delete(proto)
}
},
mockAction<I extends any[], O>(
anAction: Action<I, O>,
cb: Fn<[Ctx, ...I], O>,
) {
mockAction<I extends any[], O>(anAction: Action<I, O>, cb: Fn<[Ctx, ...I], O>) {
const proto = anAction.__reatom

throwReatomError(!proto.isAction, 'action expected')
Expand All @@ -167,5 +157,4 @@ export const createTestCtx = (options?: CtxOptions): TestCtx => {
}

/** @deprecated use `createMemStorage` fromm `@reatom/persist` instead */
export const createMockStorage = (snapshot?: Rec) =>
createMemStorage({ name: 'test', snapshot })
export const createMockStorage = (snapshot?: Rec) => createMemStorage({ name: 'test', snapshot })

0 comments on commit 5231d20

Please sign in to comment.