Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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     }) 
like image 675
Kimaya Avatar asked Jun 08 '18 13:06

Kimaya


People also ask

How do you mock data in Jest?

In Jest, Node. js modules are automatically mocked in your tests when you place the mock files in a __mocks__ folder that's next to the node_modules folder. For example, if you a file called __mock__/fs. js , then every time the fs module is called in your test, Jest will automatically use the mocks.

What is mocking in Javascript?

Mock functions allow you to test the links between code by erasing the actual implementation of a function, capturing calls to the function (and the parameters passed in those calls), capturing instances of constructor functions when instantiated with new , and allowing test-time configuration of return values.


2 Answers

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)

like image 165
iflp Avatar answered Oct 12 '22 15:10

iflp


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]})) 
like image 37
Andreas Köberle Avatar answered Oct 12 '22 14:10

Andreas Köberle