简体   繁体   English

Mocking react-cookie 中的一个 cookie

[英]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:我正在尝试在我的测试中设置一个 cookie,以确保它在我的组件中被清除:

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:但是在我的注销组件中 cookies object 是空的:

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.最好是不将 cookie 作为道具传递的。

By adding通过添加

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

According to react-cookie, you can access the cookies directly using the DOM.根据 react-cookie,您可以直接使用 DOM 访问 cookies。

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

This function is to clear cookies.这个 function 是为了清除 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可以在以下位置找到此信息及其上下文的链接: https://github.com/reactivestack/cookies/blob/master/packages/universal-cookie/src/utils.ts

So the problem was what @Oleg and @Devin were hinting at.所以问题出在@Oleg 和@Devin 所暗示的问题上。 To render the provider as well.也渲染提供者。 But I also had to pass the cookies as parameter like so:但我还必须将cookies作为参数传递,如下所示:

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>
  )
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM