cookies - 使用 Jest 测试安全 cookie 值

标签 cookies https jestjs

以前我有 Jest 代码来测试非安全 cookie 的值。它看起来像这样:
expect(Cookie.get('myToken')).toBe('tokenvalue');
(本例中的 Cookie 使用的是 js-cookie api)

但是,我尝试更新我设置 cookie 的方式,并添加了 secure标志并将其设置为 true .当测试运行时,Jest 不再能看到这个 cookie。

测试它的最佳方法是什么?

我看过类似 Jest secure cookies? 的问题

我还测试了代码并在浏览器中检查了设置了安全标志。所以这只是一个测试问题。我设置 cookie 的代码如下所示:

Cookie.set('myToken', values.user.token, {
    path: '/',
    expires: new Date(new Date().getTime() + TOKEN_DURATION),
    secure: true
});

最佳答案

我在下面试过,它奏效了

import { * as cookies } from <...ur file where cookie logic is implementated>

import Cookies from 'js-cookie';

describe('cookies functionality', () => {

    it('should set the cookie correctly', () => {
        // create a mock function using jest.fn()
        const mockSet = jest.fn();

        // here we are trying to mock the 'set' functionality of Cookie
        Cookies.set = mockSet;

        // call the set method of Cookies 
        cookies.set('key', 'value');

        // check if the mock function gets called here
        expect(mockSet).toBeCalled();
    });
});

基本上,编写单元测试是为了测试我们正在测试的单元的逻辑。如果我们使用任何外部库,那么我们可以模拟它并测试它是否被正确调用。单元测试不应该关心该库代码的实际执行,在我们这里的例子中,我们不应该在我们的单元测试中关心 Cookie 真正设置数据。如果我们可以测试 cookie 的 set/get 是否被调用,那么它应该足够好了。

关于cookies - 使用 Jest 测试安全 cookie 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55974032/

相关文章:

python请求cookies日期格式

javascript - 如何将 cookie 从 javascript 更改为 angularjs

internet-explorer - Cookie 在 IE 中不起作用

PHP 函数 getimagesize() 在尝试获取 https url 时给出 "Read error"

jestjs - Nest.js 测试模块,无法覆盖注入(inject)到另一个提供程序中的提供程序,收到未定义

swift 3 : how to check if cookies for particular URL are configured?

ssl - Spring Boot SSL 无法获得任何响应

c# - 如何在 Asp.Net Web API 上实现 Https/SSL 连接?

testing - 使用 Jest 进行测试时模拟 native 模块

javascript - 如何测试 React 组件使用 jest 渲染列表