在使用 jest 的 vue 测试中找不到模块“@jest/globals”

mat*_*rmv 4 javascript testing vue.js jestjs

我正在尝试从我的项目中的 vue 文档编写一个非常简单的测试。我可以在我的项目中使用 jest 运行测试,但是一旦我尝试使用 jest 模拟 axios 请求,就会出现以下错误:

 FAIL  tests/unit/test.spec.js
Run Code Online (Sandbox Code Playgroud)

? 测试套件无法运行

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)
Run Code Online (Sandbox Code Playgroud)

这是我的 Foo 组件:

<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>
Run Code Online (Sandbox Code Playgroud)

和相关的测试:

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()
    })
  }
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激:) 谢谢大家!

小智 8

假设你也在使用babel-jest,请确保您有两个版本jest,并babel-jest设置为26。我遇到了同样的问题,这是因为软件包版本不同步。