7

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
});
skyboyer
  • 22,209
  • 7
  • 57
  • 64
Danny
  • 73
  • 1
  • 3

1 Answers1

4

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.

Anuradha Kumari
  • 703
  • 5
  • 9