Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Jest to test secure cookie value

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');

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

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?

I've looked at questions like Jest secure cookies?

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
});
like image 941
Danny Avatar asked May 03 '19 16:05

Danny


People also ask

How do you mock cookies in Jest?

mock('universal-cookie', () => { class MockCookies { static result = {}; get() { return MockCookies. result; } } return MockCookies; }); // In your test itself: Cookies. result = { my: 'cookie_value' }; // Code under test: const cookie = new Cookies. get('whatever'); // cookie will be { my: 'cookie_value' };

Can Jest be used for browser testing?

The answer is down to Jest not being a real browser. You have access to all of the various DOM APIs when writing Jest tests but these are provided by JSDOM and your tests are actually running in Node. Jest has no native way to run your tests in a browser environment out of the box.

Is Jest good for testing?

Fast and safe. By ensuring your tests have unique global state, Jest can reliably run tests in parallel. To make things quick, Jest runs previously failed tests first and re-organizes runs based on how long test files take.


1 Answers

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();
    });
});

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.

like image 61
Anuradha Kumari Avatar answered Oct 10 '22 18:10

Anuradha Kumari