我尝试在测试中设置一个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/>)
})但是在我的注销组件中,cookies对象是空的:
export default function Logout() {
const [cookies, setCookie, removeCookie] = useCookies(['authtoken'])
console.log(cookies)
}有没有其他方法可以做到这一点?最好是不把cookie当作道具传过去的。
发布于 2019-10-14 01:24:16
所以问题是“奥列格”和“德文”在暗示什么。来呈现提供程序。但我还必须将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>
)
})发布于 2019-10-14 00:37:35
通过添加
const cookie = new Cookies();
cookie.HAS_DOCUMENT_COOKIE = false;发布于 2019-10-14 00:57:35
根据react-cookie,您可以使用DOM直接访问cookie。
document.cookie.split(';').forEach(function(c) {
document.cookie = c
.replace(/^ +/, '')
.replace(/=.*/, '=;expires=' + new Date().toUTCString() + ';path=/');
});此函数用于清除cookie。
我在前面的评论中想到的另一件事是,您可以使用cookies来呈现组件。
const cookied = withCookies(<Login />)
render(cookied)“
指向此信息及其上下文的链接可在以下位置找到:https://github.com/reactivestack/cookies/blob/master/packages/universal-cookie/src/utils.ts
https://stackoverflow.com/questions/58365446
复制相似问题