import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { FlowfulError } from '../src/error'; import { skipDevMessages } from '../src/dev'; // Mock dev module vi.mock('../src/dev', () => ({ skipDevMessages: vi.fn(), })); describe('FlowfulError', () => { const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {}); const mockSkipDevMessages = vi.mocked(skipDevMessages); beforeEach(() => { errorSpy.mockClear(); mockSkipDevMessages.mockClear(); // Default behavior for skipDevMessages unless overridden in a test mockSkipDevMessages.mockReturnValue(false); }); afterEach(() => { // Restore default mock behavior if needed, though beforeEach handles reset }); it('should create an error with message and name', () => { const error = new FlowfulError('Test message'); expect(error.message).toBe('Test message'); expect(error.name).toBe('FlowfulError'); expect(error.cause).toBeUndefined(); expect(errorSpy).not.toHaveBeenCalled(); // logCause not called if no cause }); it('should create an error with message, name, and cause', () => { const cause = new Error('Original cause'); const error = new FlowfulError('Test message with cause', cause); expect(error.message).toBe('Test message with cause'); expect(error.name).toBe('FlowfulError'); expect(error.cause).toBe(cause); }); it('should call logCause in constructor if cause exists and skipDevMessages is false', () => { mockSkipDevMessages.mockReturnValue(false); const cause = new Error('Original cause'); const error = new FlowfulError('Test message with cause', cause); expect(errorSpy).toHaveBeenCalledWith('Test message with cause Caused by:', cause); }); it('should NOT call logCause in constructor if cause exists but skipDevMessages is true', () => { mockSkipDevMessages.mockReturnValue(true); const cause = new Error('Original cause'); new FlowfulError('Test message with cause skipped', cause); // Constructor's implicit call should be skipped expect(errorSpy).not.toHaveBeenCalled(); }); it('logCause should log error and cause if cause exists', () => { const cause = new Error('Another cause'); const error = new FlowfulError('Explicit log test', cause); // Clear any calls from constructor errorSpy.mockClear(); const result = error.logCause(); expect(errorSpy).toHaveBeenCalledWith('Explicit log test Caused by:', cause); expect(result).toBe(error); // Should return the instance }); it('logCause should not log if cause does not exist', () => { const error = new FlowfulError('No cause test'); // Clear any calls from constructor (though none expected here) errorSpy.mockClear(); const result = error.logCause(); expect(errorSpy).not.toHaveBeenCalled(); expect(result).toBe(error); // Should return the instance }); });