本文介绍了如何在 JEST 中模拟 Cookie.get('language')的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个函数,它在 cookie 中设置一种语言并获取它以实现某些功能.如何在 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'
}
现在我想在 JEST 中测试它
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
})
推荐答案
不用下载任何deps,直接使用:
Don't have to download any deps, just use:
Object.defineProperty(window.document, 'cookie', {
writable: true,
value: 'myCookie=omnomnom',
});
(writable
需要设置为true)
(writable
needs to be set to true)
这篇关于如何在 JEST 中模拟 Cookie.get('language')的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!