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 })
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.
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.
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)
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]}))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With