Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking a cookie in react-cookie

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.

like image 597
dan-klasson Avatar asked May 25 '26 12:05

dan-klasson


1 Answers

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>
  )
})
like image 116
dan-klasson Avatar answered May 27 '26 19:05

dan-klasson