Reactjs 在cookie中模仿cookie
我试图在测试中设置cookie,以确保它在我的组件中被清除:Reactjs 在cookie中模仿cookie,reactjs,react-cookie,Reactjs,React Cookie,我试图在测试中设置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/>) })
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/>)
})
还有别的办法吗?最好是不将cookie作为道具传递的道具。通过添加
const cookie = new Cookies();
cookie.HAS_DOCUMENT_COOKIE = false;
根据react cookie,您可以使用DOM直接访问cookie
document.cookie.split(';').forEach(function(c) {
document.cookie = c
.replace(/^ +/, '')
.replace(/=.*/, '=;expires=' + new Date().toUTCString() + ';path=/');
});
此函数用于清除Cookie
我在前面的评论中还考虑了一个问题,即您可以通过“
const cookied=withCookies()
渲染(烹饪)
"
有关此信息及其上下文的链接,请访问:,因此问题在于@Oleg和@Devin所暗示的内容。也要呈现提供程序。但我还必须将
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>
)
})
从“通用cookie”导入cookie;
测试('成功注销用户',异步()=>{
const cookie=新cookie({authtoken:'some token'});
常量{getByText}=render(
)
})
我不知道这两个软件包的内部工作原理,但似乎您正在尝试使用两个不同的cookie软件包;反应饼干和通用饼干。如果使用ssr,请使用第一个,否则使用第二个。您还有其他可能有用的上下文吗?@Devin一个包与另一个包有依赖关系。我认为这确实是一个react cookie
问题。react cookie中的cookie是根据上下文提供的。是否可能因为未呈现cookie提供程序而未提供cookie?文档示例导出默认函数Root(){return();}@Devin我也尝试将
放入render
方法中。但是仍然没有骰子。Logout
组件中的cookies
对象仍然是空的,不幸的是,查看更多用例的示例:Try without hook,cookie.getYeah,console.log(document.cookie)
也是空的。可能是钩的东西。但是一定有办法做到这一点不?试着像document.cookie='test='+cookieValue;这应该与文档相同。cookie='foo'
否?我也试过了,但不幸的是没有骰子。根据文档和cookies
设置了一些组件上的道具,这不是我想要的。也试过了,但仍然没有luckWell,我正在开发自己的ssr应用程序。我现在要在全球层面上整合cookies。如果我遇到这个问题,我会让你知道,如果我没有遇到,我会告诉你为什么它会起作用。请参阅我的答案以获得解决方案。但这并不是很理想,因为我所做的只是传入cookie,以便它在组件中可用。
const cookied = withCookies(<Login />)
render(cookied)
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>
)
})