@vergiss/chooks
Version:
React hooks library
50 lines • 1.74 kB
JavaScript
import "core-js/modules/es.date.to-string";
import { act, renderHook } from '@testing-library/react-hooks';
import { useLocalStorage } from '../index';
var mockTimestamp = 0;
jest.spyOn(Date, 'now').mockImplementation(function () {
return mockTimestamp;
});
describe('useLocalStorage', function () {
it('should be defined', function () {
expect(useLocalStorage).toBeDefined();
});
it('should set a value to localStorage', function () {
var key = 'test';
var hook = renderHook(function () {
return useLocalStorage(key, 'hello');
});
var storage = hook.result.current[0];
expect(storage).toBe('hello');
expect(global.window.localStorage.getItem(key)).toBe('"hello"');
});
it('should update the storage', function () {
var key = 'test';
var hook = renderHook(function () {
return useLocalStorage(key, 'hello');
});
expect(hook.result.current[0]).toBe('hello');
expect(global.window.localStorage.getItem(key)).toBe('"hello"');
act(function () {
hook.result.current[1]('world');
});
expect(hook.result.current[0]).toBe('world');
expect(global.window.localStorage.getItem(key)).toBe('"world"');
});
it('should get empty value after expiration age', function () {
var key = 'text-expiration';
var hook = renderHook(function () {
return useLocalStorage(key, 'value', {
expireAge: 2000
});
});
expect(hook.result.current[0]).toBe('value');
expect(global.window.localStorage.getItem(key)).toBe('"value"');
act(function () {
mockTimestamp += 2300;
hook.rerender();
});
expect(hook.result.current[0]).toBe(null);
expect(global.window.localStorage.getItem(key)).toBe(null);
});
});