Mocking a cookie in react-cookie

3.9k Views Asked by At

I'm trying to set a cookie in my test to make sure it's getting cleared out in my component:

import Cookies from 'universal-cookie';

test('successfully logs the user out', async () => {
  const cookie = new Cookies()
  cookie.set('authtoken', 'some-token')
  const { getByText } = render(<Logout/>)
})

But in my Logout component the cookies object is empty:

export default function Logout() {
  const [cookies, setCookie, removeCookie] = useCookies(['authtoken'])
  console.log(cookies)
}

Is there another way to do this? Preferably one that isn't passing the cookie as a prop.

3

There are 3 best solutions below

12
On

By adding

 const cookie = new Cookies();
 cookie.HAS_DOCUMENT_COOKIE = false;
4
On

According to react-cookie, you can access the cookies directly using the DOM.

 document.cookie.split(';').forEach(function(c) {
    document.cookie = c
      .replace(/^ +/, '')
      .replace(/=.*/, '=;expires=' + new Date().toUTCString() + ';path=/');
 });

This function is to clear cookies.

Something else that I was thinking in an earlier comment was that you render the component with cookies via "

const cookied = withCookies(<Login />)
render(cookied)

"

A link to this information and it's context can be found at: https://github.com/reactivestack/cookies/blob/master/packages/universal-cookie/src/utils.ts

0
On

So the problem was what @Oleg and @Devin were hinting at. To render the provider as well. But I also had to pass the cookies as parameter like so:

import Cookies from 'universal-cookie';

test('successfully logs the user out', async () => {
  const cookie = new Cookies({authtoken: 'some-token'});
  const { getByText } = render(
    <CookiesProvider cookies={cookie}>
      <Router>
        <Logout/>
      </Router>
    </CookiesProvider>
  )
})