Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
589 views
in Technique[技术] by (71.8m points)

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

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
    })
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...