[英]Vue + Jest mocking global method
I'm working on a project that has a method defined in the script tag of the index.html
file. 我正在一个项目中,该项目具有在
index.html
文件的script标记中定义的方法。 For some reason, that causes Jest to fail when it runs. 由于某种原因,这会导致Jest在运行时失败。
index.html
<script>
var getCookie = function(cookieVal) { return cookieVal; }
</script>
To fix this, I've tried defining the 'getCookie' variable inside of Jest globals like: 为了解决这个问题,我尝试在Jest全局变量中定义“ getCookie”变量,例如:
package.json
"jest": {
"globals": {
"getCookie": "someString"
}
}
This does define getCookie
, but when I run my tests I get this error: 这确实定义了
getCookie
,但是当我运行测试时,出现此错误:
Error in data(): "TypeError: getCookie is not a function"
data()中的错误:“ TypeError:getCookie不是函数”
which makes sense, but I'm not sure how I can define it as a function in the globals
object. 这很有意义,但是我不确定如何在
globals
对象中将其定义为函数。
How can I mock my getCookie
function in Jest? 如何在Jest中模拟我的
getCookie
函数?
Even though the Jest docs indicate that globals
cannot contain functions , I verified that global functions could still be defined with a function expression or arrow function : 即使Jest文档指出
globals
不能包含函数 ,但我还是验证了仍然可以使用函数表达式或箭头函数定义全局函数 :
{
jest: {
globals: {
getCookie() { return 'someCookie' }, // function expression
getCookie: () => 'someCookie', // arrow function
}
}
}
Alternatively, you could define a setupFiles
that sets global.getCookie
: 或者,您可以定义设置
global.getCookie
的setupFiles
:
// package.json
{
jest: {
setupFiles: ['./jest.setup.js']
}
}
// jest.setup.js
global.getCookie = () => 'someCookie'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.