首页 > 解决方案 > 模拟 Cookie 存储以返回自定义响应对象

问题描述

我在使用cookieStore.

我怎样才能模拟cookieStore成为一个有效的对象并让它有
相关的值来测试它?

我希望模拟它,使其cookieStore在我执行 get 时等于跟随对象。

cookieStore.get('myCookie')应该返回以下对象。

{
    'name' : 'cookiename',
    'expires' : '679543860927183',
}

这是函数(如果相关,它是异步的)。

const checkCookie = async () => {

  const exists = typeof cookieStore === 'object';
  if (!exists) {
    // right now cookieStore always doesn't exist in test 
    // thus always end up here. 
    return 'store not found';
  }

  const myCookie = await cookieStore.get('mycookie');
  const {expires} = { ...myCookie };

  if (expires) {
    return 'cookie expired';
  }
}

目前测试失败,因为 cookieStore 未定义

it('should return cookie expired text', async () => {
    const result = await checkCookie();
    expect(result).toBe('cookie expired');
});

注意:我没有导入cookieStore. 它是一个有效的网络 API。您可以转到 Chrome
浏览器的控制台并键入cookieStore以查看它是否存在。

因此实际上可以按原样复制上述功能。

文档cookieStore供参考:https ://developer.mozilla.org/en-US/docs/Web/API/CookieStore

标签: javascriptjestjs

解决方案


推荐阅读