Skip to content

Commit

Permalink
test: check console output
Browse files Browse the repository at this point in the history
  • Loading branch information
trajano committed Dec 1, 2024
1 parent c4bf4be commit 91493ce
Showing 1 changed file with 67 additions and 0 deletions.
67 changes: 67 additions & 0 deletions packages/my-hooks/src/useWhyEffect.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,18 @@ import { useState } from 'react';
import { useWhyEffect } from './useWhyEffect';

describe('useWhyEffect', () => {
it('should be quiet if there are no dependencies', () => {
const logSpy = jest.spyOn(console, 'debug').mockImplementation();
const mockEffect = jest.fn();
renderHook(() => {
useWhyEffect(mockEffect, []);
return {};
});
expect(mockEffect).toHaveBeenCalledTimes(1);
expect(logSpy).not.toHaveBeenCalled();
logSpy.mockRestore();
});

it('should detect changes in dependencies and trigger the callback with the correct indices', () => {
const mockEffect = jest.fn();
const mockOnChange = jest.fn();
Expand Down Expand Up @@ -56,4 +68,59 @@ describe('useWhyEffect', () => {
expect(mockOnChange).toHaveBeenCalledWith([0, 2]);
expect(mockEffect).toHaveBeenCalledTimes(1); // Effect runs again
});

it('should detect changes in dependencies and trigger the callback with the correct indices using default logger', () => {
const mockEffect = jest.fn();
const logSpy = jest.spyOn(console, 'debug').mockImplementation();

const { result } = renderHook(() => {
const [deps, setDeps] = useState<any[]>([1, 'test', true]);

useWhyEffect(mockEffect, deps);

return { setDeps };
});

// Initially, no changes should be detected
expect(logSpy).not.toHaveBeenCalled();
expect(mockEffect).toHaveBeenCalledTimes(1);

// Clear mocks for the next step
mockEffect.mockClear();
logSpy.mockClear();

// Update dependencies manually using act
act(() => {
result.current.setDeps([2, 'test', true]); // First dependency changes
});

// Now the mockOnChange should have been called with the index of the changed dependency
expect(logSpy).toHaveBeenCalledWith('changedIndices: 0');
expect(mockEffect).toHaveBeenCalledTimes(1); // Effect runs again

// Clear mocks for the next step
mockEffect.mockClear();
logSpy.mockClear();

// Another change in dependencies
act(() => {
result.current.setDeps([2, 'newTest', true]); // Second dependency changes
});

expect(logSpy).toHaveBeenCalledWith('changedIndices: 1');
expect(mockEffect).toHaveBeenCalledTimes(1);

// Clear mocks for the next step
mockEffect.mockClear();
logSpy.mockClear();

// Multiple changes in dependencies
act(() => {
result.current.setDeps([3, 'newTest', false]); // First and third dependencies change
});

expect(mockEffect).toHaveBeenCalledTimes(1); // Effect runs again
expect(logSpy).toHaveBeenCalledWith('changedIndices: 0,2');
logSpy.mockRestore();
});
});

0 comments on commit 91493ce

Please sign in to comment.