import {getStorageValue, useLocalStorage} from './useLocalStorage'
import {cleanup, render, screen} from "@testing-library/react";

describe('getStorageValue', () => {
    it('getting stored value', () => {
        let val = getStorageValue('key', 'defaultValue');
        expect(val).toBe('defaultValue');

        localStorage.setItem('key', JSON.stringify('value'));
        val = getStorageValue('key', 'defaultValue');
        expect(val).toBe('value');
    });
})


describe('useLocalStorage', () => {
    beforeEach(() => {
        const TestComponent = () => {
            const [value, setValue] = useLocalStorage('key2', 'defaultValue');
            return (
                <div>
                    <button data-testid="setVal" onClick={() => setValue('newValue')}>Set Value</button>
                    <div data-testid="val">{value}</div>
                </div>
            );
        }

        render(<TestComponent/>);
    });

    afterEach(() => {
        cleanup();
    });


    it('getting default value and setting it', () => {
        expect(screen.getByTestId('val').innerHTML).toEqual('defaultValue');
        screen.getByTestId('setVal').click();
        expect(screen.getByTestId('val').innerHTML).toEqual('newValue');
    });
})