From eb1391ab1839c048a5c160233beb4712e24c2e7c Mon Sep 17 00:00:00 2001 From: gru-bot Date: Thu, 26 Sep 2024 22:16:35 +0800 Subject: [PATCH] test: add unit test for src/vanilla/utils/atomWithObservable.ts --- .../utils/atomWithObservable.gru.test.ts | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 src/vanilla/utils/atomWithObservable.gru.test.ts diff --git a/src/vanilla/utils/atomWithObservable.gru.test.ts b/src/vanilla/utils/atomWithObservable.gru.test.ts new file mode 100644 index 0000000000..fb1dfb490b --- /dev/null +++ b/src/vanilla/utils/atomWithObservable.gru.test.ts @@ -0,0 +1,61 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ +/* eslint-disable @typescript-eslint/no-unused-vars */ +/* eslint-disable @typescript-eslint/no-explicit-any */ +/* eslint-disable @typescript-eslint/no-unused-vars */ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { atom } from '../../vanilla.ts' +import { atomWithObservable } from './atomWithObservable.ts' + +describe('atomWithObservable', () => { + let mockObservable: any + let mockSubject: any + + beforeEach(() => { + mockObservable = { + subscribe: vi.fn(() => ({ + unsubscribe: vi.fn(), + })), + } + + mockSubject = { + ...mockObservable, + next: vi.fn(), + } + }) + + it('should create an atom with observable', () => { + const observableAtom = atomWithObservable(() => mockObservable, { + initialValue: 'initial', + }) + expect(observableAtom).toBeDefined() + }) + + it('should handle next calls on subject', () => { + const observableAtom = atomWithObservable(() => mockSubject, { + initialValue: 'initial', + }) + const mockGet = vi.fn(() => ['initial']) + const result = atom((get) => + observableAtom.read(get, { get: mockGet } as any), + ) + mockSubject.next('test') + expect(mockSubject.next).toHaveBeenCalledWith('test') + }) + + it('should handle errors', () => { + const error = new Error('Test error') + mockObservable.subscribe = vi.fn((observer: any) => { + observer.error?.(error) + return { unsubscribe: vi.fn() } + }) + const observableAtom = atomWithObservable(() => mockObservable, { + initialValue: 'initial', + }) + const mockGet = vi.fn(() => ['initial']) + try { + atom((get) => observableAtom.read(get, { get: mockGet } as any)) + } catch (e) { + expect(e).toBe(error) + } + }) +})