Vue + Jest 模拟全局方法
Vue + Jest mocking global method
我正在开发一个项目,该项目在 index.html
文件的脚本标记中定义了一个方法。出于某种原因,这会导致 Jest 在 运行s.
时失败
index.html
<script>
var getCookie = function(cookieVal) { return cookieVal; }
</script>
为了解决这个问题,我尝试在 Jest 全局变量中定义 'getCookie' 变量,例如:
package.json
"jest": {
"globals": {
"getCookie": "someString"
}
}
这确实定义了 getCookie
,但是当我 运行 我的测试时,我得到了这个错误:
Error in data(): "TypeError: getCookie is not a function"
这是有道理的,但我不确定如何将它定义为 globals
对象中的函数。
如何在 Jest 中模拟我的 getCookie
函数?
尽管 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: {
getCookie() { return 'someCookie' }, // function expression
getCookie: () => 'someCookie', // arrow function
}
}
}
或者,您可以定义一个 setupFiles
来设置 global.getCookie
:
// package.json
{
jest: {
setupFiles: ['./jest.setup.js']
}
}
// jest.setup.js
global.getCookie = () => 'someCookie'
我正在开发一个项目,该项目在 index.html
文件的脚本标记中定义了一个方法。出于某种原因,这会导致 Jest 在 运行s.
index.html
<script>
var getCookie = function(cookieVal) { return cookieVal; }
</script>
为了解决这个问题,我尝试在 Jest 全局变量中定义 'getCookie' 变量,例如:
package.json
"jest": {
"globals": {
"getCookie": "someString"
}
}
这确实定义了 getCookie
,但是当我 运行 我的测试时,我得到了这个错误:
Error in data(): "TypeError: getCookie is not a function"
这是有道理的,但我不确定如何将它定义为 globals
对象中的函数。
如何在 Jest 中模拟我的 getCookie
函数?
尽管 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: {
getCookie() { return 'someCookie' }, // function expression
getCookie: () => 'someCookie', // arrow function
}
}
}
或者,您可以定义一个 setupFiles
来设置 global.getCookie
:
// package.json
{
jest: {
setupFiles: ['./jest.setup.js']
}
}
// jest.setup.js
global.getCookie = () => 'someCookie'