2

How can I test Cookies.get with jest testing

I have util.js folder where I call function

const fullObjectStr = Cookies.get(cookieName);

So, I want to test it with jest. How can I do that?

I've tried a few things from this question: How to mock Cookie.get('language') in JEST but it doesn't work.

Lin Du
  • 88,126
  • 95
  • 281
  • 483
Sveto
  • 33
  • 1
  • 3

1 Answers1

2

You can use jest.spyOn(object, methodName) to mock Cookies.get method.

E.g. main.js:

import Cookies from 'js-cookie';

export function main(cookieName) {
  const fullObjectStr = Cookies.get(cookieName);
  console.log(fullObjectStr);
}

main.test.js:

import { main } from './main';
import Cookies from 'js-cookie';

describe('61364508', () => {
  it('should pass', () => {
    const getSpy = jest.spyOn(Cookies, 'get').mockReturnValueOnce('123');
    const cookieName = 'sid';
    main(cookieName);
    expect(getSpy).toBeCalledWith(cookieName);
    getSpy.mockRestore();
  });
});

unit test results:

 PASS  stackoverflow/61364508/main.test.js (14.388s)
  61364508
    ✓ should pass (43ms)

  console.log stackoverflow/61364508/main.js:5
    123

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        16.256s

source code: https://github.com/mrdulin/react-apollo-graphql-starter-kit/tree/master/stackoverflow/61364508

Lin Du
  • 88,126
  • 95
  • 281
  • 483