繁体   English   中英

Vue + Jest模拟全局方法

[英]Vue + Jest mocking global method

我正在一个项目中,该项目具有在index.html文件的script标记中定义的方法。 由于某种原因,这会导致Jest在运行时失败。

index.html

<script>
var getCookie = function(cookieVal) { return cookieVal; }
</script>

为了解决这个问题,我尝试在Jest全局变量中定义“ getCookie”变量,例如:

package.json

"jest": {
  "globals": {
      "getCookie": "someString"
    }
}

这确实定义了getCookie ,但是当我运行测试时,出现此错误:

data()中的错误:“ TypeError:getCookie不是函数”

这很有意义,但是我不确定如何在globals对象中将其定义为函数。

如何在Jest中模拟我的getCookie函数?

即使Jest文档指出globals不能包含函数 ,但我还是验证了仍然可以使用函数表达式箭头函数定义全局函数

{
  jest: {
    globals: {
      getCookie() { return 'someCookie' },  // function expression
      getCookie: () => 'someCookie',        // arrow function
    }
  }
}

或者,您可以定义设置global.getCookiesetupFiles

// package.json
{
  jest: {
    setupFiles: ['./jest.setup.js']
  }
}

// jest.setup.js
global.getCookie = () => 'someCookie'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM