使用Jest测试安全的Cookie值 [英] Use Jest to test secure cookie value

查看:695
本文介绍了使用Jest测试安全的Cookie值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以前,我有Jest代码来测试非安全cookie的值.看起来像这样:

Previously I had Jest code to test for the value of a non-secure cookie. It looked like this:

expect(Cookie.get('myToken')).toBe('tokenvalue');

(本例中的Cookie使用的是js-cookie api)

(the Cookie in this instance is using the js-cookie api)

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

However, I tried to update how I set my cookie, and added the secure flag and set it to true. Jest no longer can see this cookie when the test runs.

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

What's the best way to test it?

我看过诸如最好的安全cookie之类的问题?

我还测试了代码,并在浏览器中检查了安全标志的设置.因此,这只是一个测试问题.我设置Cookie的代码如下:

I've also tested the code and checked in a browser that the secure flag is set. So this is just a testing issue. My code to set the cookie looks like this:

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

推荐答案

我在下面尝试了并且有效

I tried below and it worked

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实际设置数据而感到烦恼.如果我们可以测试是否调用了set/get cookie,那么就足够了.

Basically unit tests are written to test the logic of the unit which we are testing. If we are using any external library then we can just mock it and test that it is getting called properly. The unit test should not bother about the real execution of that library code, in our case here, we should not be bothered in our unit test about the Cookie really setting the data. If we can test that set/get of cookies is getting called, then it should be good enough.

这篇关于使用Jest测试安全的Cookie值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆