Edon
Edon

Reputation: 1216

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. For some reason, that causes Jest to fail when it runs.

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:

package.json

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

This does define getCookie, but when I run my tests I get this error:

Error in data(): "TypeError: getCookie is not a function"

which makes sense, but I'm not sure how I can define it as a function in the globals object.

How can I mock my getCookie function in Jest?

Upvotes: 0

Views: 530

Answers (1)

tony19
tony19

Reputation: 138196

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: {
      getCookie() { return 'someCookie' },  // function expression
      getCookie: () => 'someCookie',        // arrow function
    }
  }
}

Alternatively, you could define a setupFiles that sets global.getCookie:

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

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

Upvotes: 1

Related Questions