Reputation: 14190
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.
Upvotes: 3
Views: 4414
Reputation: 14190
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>
)
})
Upvotes: 2
Reputation: 134
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
Upvotes: 0
Reputation: 3621
By adding
const cookie = new Cookies();
cookie.HAS_DOCUMENT_COOKIE = false;
Upvotes: 0