5

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 !

0

3 Answers 3

12

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for help. In facti removed "moduleDirectories": [ "node_modules", "src" ], "modulePaths": [ "<rootDir>/node_modules" ], from my jest.config.js file and all worked like a charm :)
0

In my case, this error happens in [email protected]. After downgrade to [email protected], problem disappear.

Comments

0

I had the same problem. Fixed with lowering the jest libraries' versions to be the same as of ts-jest:

    "@jest/globals": "29.1.1",
    "jest": "29.1.1",
    "jest-environment-jsdom": "29.1.1",
    "ts-jest": "29.1.1"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.