Skip to content

Commit

Permalink
Added vitest
Browse files Browse the repository at this point in the history
Started to add tests but this will lay the path.
  • Loading branch information
dustinwloring1988 committed Nov 30, 2024
1 parent fe45651 commit c05e6f5
Show file tree
Hide file tree
Showing 8 changed files with 23,602 additions and 8 deletions.
131 changes: 131 additions & 0 deletions app/lib/hooks/usePromptEnhancer.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
import { renderHook, act } from '@testing-library/react';
import { usePromptEnhancer } from './usePromptEnhancer';
import { describe, it, expect, beforeEach, vi } from 'vitest';

// Mock fetch globally
global.fetch = vi.fn();

const mockReader = {
read: vi.fn(),
};
const mockGetReader = vi.fn(() => mockReader);

// Create a simple TextDecoder mock that implements the required interface
class MockTextDecoder implements TextDecoder {
encoding: string = 'utf-8';
fatal: boolean = false;
ignoreBOM: boolean = false;
decode(_value?: BufferSource): string {
return 'Enhanced prompt';
}
}

beforeEach(() => {
vi.clearAllMocks();
(global.fetch as any).mockReset();
global.TextDecoder = MockTextDecoder as any;
});

describe('usePromptEnhancer', () => {
const defaultModel = 'gpt-4';
const defaultProvider = {
id: 'openai',
name: 'OpenAI',
staticModels: [{ name: 'gpt-4', label: 'GPT-4', provider: 'OpenAI', maxTokenAllowed: 8000 }],
};

it('should initialize with default values', () => {
const { result } = renderHook(() => usePromptEnhancer());

expect(result.current.enhancingPrompt).toBe(false);
expect(result.current.promptEnhanced).toBe(false);
expect(typeof result.current.enhancePrompt).toBe('function');
expect(typeof result.current.resetEnhancer).toBe('function');
});

it('should reset state when resetEnhancer is called', () => {
const { result } = renderHook(() => usePromptEnhancer());

act(() => {
result.current.resetEnhancer();
});

expect(result.current.enhancingPrompt).toBe(false);
expect(result.current.promptEnhanced).toBe(false);
});

it('should enhance prompt successfully', async () => {
const mockResponse = {
body: {
getReader: mockGetReader,
},
};
mockReader.read
.mockResolvedValueOnce({ value: new TextEncoder().encode('Enhanced'), done: false })
.mockResolvedValueOnce({ value: new TextEncoder().encode(' prompt'), done: false })
.mockResolvedValueOnce({ value: undefined, done: true });

(global.fetch as any).mockResolvedValueOnce(mockResponse);

const { result } = renderHook(() => usePromptEnhancer());
const setInput = vi.fn();

await act(async () => {
await result.current.enhancePrompt('Original prompt', setInput, defaultModel, defaultProvider);
});

expect(result.current.enhancingPrompt).toBe(false);
expect(result.current.promptEnhanced).toBe(true);
expect(setInput).toHaveBeenCalledWith('Enhanced prompt');
});

it('should handle errors during prompt enhancement', async () => {
const mockResponse = {
body: {
getReader: mockGetReader,
},
};
mockReader.read.mockRejectedValueOnce(new Error('Enhancement failed'));
(global.fetch as any).mockResolvedValueOnce(mockResponse);

const { result } = renderHook(() => usePromptEnhancer());
const setInput = vi.fn();
const originalPrompt = 'Original prompt';

await act(async () => {
await result.current.enhancePrompt(originalPrompt, setInput, defaultModel, defaultProvider).catch(() => {
// Error is expected
});
});

expect(result.current.enhancingPrompt).toBe(false);
expect(result.current.promptEnhanced).toBe(true);
expect(setInput).toHaveBeenCalledWith(originalPrompt);
});

it('should include API keys in request when provided', async () => {
const mockResponse = {
body: {
getReader: mockGetReader,
},
};
mockReader.read.mockResolvedValueOnce({ value: undefined, done: true });
(global.fetch as any).mockResolvedValueOnce(mockResponse);

const { result } = renderHook(() => usePromptEnhancer());
const setInput = vi.fn();
const apiKeys = { openai: 'test-key' };

await act(async () => {
await result.current.enhancePrompt('Original prompt', setInput, defaultModel, defaultProvider, apiKeys);
});

expect(global.fetch).toHaveBeenCalledWith(
'/api/enhancer',
expect.objectContaining({
method: 'POST',
body: expect.stringContaining('test-key'),
}),
);
});
});
9 changes: 5 additions & 4 deletions app/lib/runtime/action-runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ export class ActionRunner {
});
}

async runAction(data: ActionCallbackData, isStreaming: boolean = false) {
async runAction(data: ActionCallbackData, isStreaming: boolean = false): Promise<void> {
const { actionId } = data;
const action = this.actions.get()[actionId];

Expand All @@ -84,11 +84,11 @@ export class ActionRunner {
}

if (action.executed) {
return;
return Promise.resolve();
}

if (isStreaming && action.type !== 'file') {
return;
return Promise.resolve();
}

this.#updateAction(actionId, { ...action, ...data.action, executed: !isStreaming });
Expand All @@ -100,7 +100,8 @@ export class ActionRunner {
.catch((error) => {
console.error('Action failed:', error);
});
return this.#currentExecutionPromise;

return this.#currentExecutionPromise;
}

async #executeAction(actionId: string, isStreaming: boolean = false) {
Expand Down
8 changes: 5 additions & 3 deletions app/utils/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -283,9 +283,11 @@ const getOllamaBaseUrl = () => {
};

async function getOllamaModels(): Promise<ModelInfo[]> {
//if (typeof window === 'undefined') {
//return [];
//}
/*
* if (typeof window === 'undefined') {
* return [];
* }
*/

try {
const baseUrl = getOllamaBaseUrl();
Expand Down
2 changes: 1 addition & 1 deletion app/utils/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ interface Logger {
setLevel: (level: DebugLevel) => void;
}

let currentLevel: DebugLevel = import.meta.env.VITE_LOG_LEVEL ?? import.meta.env.DEV ? 'debug' : 'info';
let currentLevel: DebugLevel = (import.meta.env.VITE_LOG_LEVEL ?? import.meta.env.DEV) ? 'debug' : 'info';

const isWorker = 'HTMLRewriter' in globalThis;
const supportsColor = !isWorker;
Expand Down
Loading

0 comments on commit c05e6f5

Please sign in to comment.