File size: 1,707 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import { renderHook, act } from '@testing-library/react-hooks';
import Cookies from 'js-cookie';
import { useCookie } from '../src';

const setup = (cookieName: string) => renderHook(() => useCookie(cookieName));

it('should have initial value of null if no cookie exists', () => {
  const { result } = setup('some-cookie');

  expect(result.current[0]).toBeNull();
});

it('should have initial value of the cookie if it exists', () => {
  const cookieName = 'some-cookie';
  const value = 'some-value';
  Cookies.set(cookieName, value);

  const { result } = setup(cookieName);

  expect(result.current[0]).toBe(value);

  // cleanup
  Cookies.remove(cookieName);
});

it('should update the cookie on call to updateCookie', () => {
  const spy = jest.spyOn(Cookies, 'set');

  const cookieName = 'some-cookie';
  const { result } = setup(cookieName);

  const newValue = 'some-new-value';
  act(() => {
    result.current[1](newValue);
  });

  expect(result.current[0]).toBe(newValue);
  expect(spy).toHaveBeenCalledTimes(1);
  expect(spy).toHaveBeenCalledWith(cookieName, newValue, undefined);

  // cleanup
  spy.mockRestore();
  Cookies.remove(cookieName);
});

it('should delete the cookie on call to deleteCookie', () => {
  const cookieName = 'some-cookie';
  const value = 'some-value';
  Cookies.set(cookieName, value);

  const spy = jest.spyOn(Cookies, 'remove');

  const { result } = setup(cookieName);

  expect(result.current[0]).toBe(value);

  act(() => {
    result.current[2]();
  });

  expect(result.current[0]).toBeNull();
  expect(spy).toHaveBeenCalledTimes(1);
  expect(spy).toHaveBeenLastCalledWith(cookieName);

  // cleanup
  spy.mockRestore();
  Cookies.remove(cookieName);
});