How to mock Cookie.get('language') in JEST

2020-07-04 08:06发布

I have a function which sets a language in cookie and gets it for some functionality. How do I set the value of language correctly for testing in JEST

function resolveLanguage () {
  // browser cookie is checked to see if there is a value for language
  const lang = Cookie.get('language')

  // If no lang, it is defaulted to en 
  return lang || 'en'
}

Now I want to test it in JEST

it('can resolve the language using a cookie', () => {
      Cookie.__defineGetter__("language", function() {
        return 'fr'
      })
      // console.log(Cookie.language) //returns fr
      // console.log(Cookie.get('language')) //returns fr
      expect(module.resolveLanguage()).toBe('fr') ---FAILS because it returns en
    })

5条回答
来,给爷笑一个
2楼-- · 2020-07-04 08:11

Don't have to download any deps, just use:

Object.defineProperty(window.document, 'cookie', {
            writable: true,
            value: 'myCookie=omnomnom',
        });

(writable needs to be set to true)

查看更多
叛逆
3楼-- · 2020-07-04 08:14

When using the setFilesAfterEnv option in JEST, adding the following to the defined setup file works pretty well.

Enables normal cookie handling without any mocking.

let __cookies;
Object.defineProperty( window.document, 'cookie', {
    get: () => __cookies,
    set: v => __cookies = v,
    slit: s => __cookies.split( s ),
} );
查看更多
Fickle 薄情
4楼-- · 2020-07-04 08:22

I tried this and it worked:

import Cookies from 'js-cookie';

Cookies.get = jest.fn()
    .mockImplementation(() => 'fr');

If you want to return different values each time you call Cookies.get(), you can do this:

Cookies.get = jest.fn()
    .mockImplementationOnce(() => 'en') // first time
    .mockImplementationOnce(() => 'de'); // second time
查看更多
看我几分像从前
5楼-- · 2020-07-04 08:24

The below code helped with mocking set/get for cookies for all types of tests in Jest:

Object.defineProperty(document, "doctype", {
 value: "<!DOCTYPE html>"
});
let setCookie = (v) => v;

Object.defineProperty(window.navigator, 'cookieEnabled', (function (_value) {
  return {
    get: function _get() {
      return _value;
    },
    set: function _set(v) {
    _value = v;
    },
    configurable: true
  };
})(window.navigator.cookieEnabled));

setCookie = (v) => v;

Object.defineProperty(window.document, 'cookie', (function (_value) {
  return {
    get: function _get() {
      return _value;
    },
    set: function _set(v) {
      _value = setCookie(v);
    },
    configurable: true
  };
})(window.navigator.cookieEnabled));
查看更多
在下西门庆
6楼-- · 2020-07-04 08:27

You need to mock js-cookie using jest to set the language set you want.

import Cookie from 'js-cookie'

jest.mock('js-cookie', ()=> jest.fn())

Cookie.setMockImplementation(()=>({get: () => 'fr'}))

Or if you only need to set it once

jest.mock('js-cookie', ()=>({get: () => 'fr'}))

Note that this solution would always return 'fr' for all Cookie.get calls. If you need support multiple values on get you could do something like this:

jest.mock('js-cookie', ()=>({get: key => {
   language: 'fr', 
   somethingElse: 'someThing'
}[key]}))
查看更多
登录 后发表回答