Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot find module '@jest/globals' in a vue test using jest

I am trying to write a really simple test from vue documentation inside my Project. I can run tests with jest in my project, but as soon as i am trying to mock axios request with jest, i have this error :

 FAIL  tests/unit/test.spec.js

● Test suite failed to run

Cannot find module '@jest/globals' from 'test.spec.js'

  14 |   })

  at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:259:17)
  at _getJestObj (tests/unit/test.spec.js:16:7)
  at Object.<anonymous> (tests/unit/test.spec.js:3:1)

Here is my Foo component :

<template>
  <button @click="fetchResults">{{ value }}</button>
</template>

<script>
  import axios from 'axios'

  export default {
    data() {
      return {
        value: null
      }
    },

    methods: {
      async fetchResults() {
        const response = await axios.get('mock/service')
        this.value = response.data
      }
    }
  }
</script>

And the test associated :

import { shallowMount } from '@vue/test-utils'
import Foo from './Foo'
jest.mock('axios', () => ({
  get: Promise.resolve('value')
}))

it('fetches async when a button is clicked', done => {
    const wrapper = shallowMount(Foo)
    wrapper.find('button').trigger('click')
    wrapper.vm.$nextTick(() => {
      expect(wrapper.text()).toBe('value')
      done()
    })
  }

Any help would be appreciated :) Thanks guys !

like image 562
matirmv Avatar asked Jan 01 '23 02:01

matirmv


1 Answers

Assuming that you are also using babel-jest, make sure you have both versions of jest and babel-jest set to same numer (24, 26` etc.). I had the same problem and it was because the package versions were not in sync.


If you're using npm 7+, then peer dependencies are automatically installed and you could end up with two different versions of babel-jest used simultaneously. You can disable that behavior by adding

legacy-peer-deps=true

into .npmrc file.

like image 72
Arkaitz Garro Avatar answered Jan 13 '23 11:01

Arkaitz Garro