跟随玩笑的文档来模拟axios,但无法正常工作

时间:2018-11-18 03:40:12

标签: javascript testing mocking axios jestjs

我将玩笑的文档传送到模拟模块'axios'

像这样

// httpCall.js
import axios from 'axios'
export default function httpCall () {
  return axios.get('url/to/the/end/point').then(res => res.data)
}

和我的测试文件

import axios from 'axios'
import httpCall from './index'
jest.mock('axios')
test('mock module axios', () => {
  const resp = { data: { id: 1, name: 'John Doe' } }
  axios.mockResolvedValue(resp)
  return httpCall().then(res => expect(res).toEqual(resp.data))
})

然后出现此错误

TypeError: _axios.default.mockResolvedValue is not a function

所以我尝试用Google搜索它,然后尝试Mock inner axios.create()

创建模拟 /axios-mock.js

const mockAxios = jest.genMockFromModule('axios')
mockAxios.create = jest.fn(() => mockAxios)
export default mockAxios

然后将我的测试文件更新为此

import mockAxios from './__mocks__/axios-mock'
import httpCall from './index'
test('mock module axios', () => {
  const resp = { data: { id: 1, name: 'John Doe' } }
  mockAxios.get.mockResolvedValue(resp)
  return httpCall().then(res => expect(res).toEqual(resp.data))
})

但仍然出现如下错误

Request failed with status code 404

我对此一无所知...但是最终我使它起作用了。

这是我的模拟文件

// __mocks__/axios-mock.js
import axios from 'axios'
const mockAxios = jest.genMockFromModule('axios')
export default axios

// or even like this
import axios from 'axios'
jest.mock('axios')
export default axios

这是我的测试文件

import httpCall from './index'
import mockAxios from './__mocks__/axios-mock'

describe('mock module', () => {
  it('axios should be mocked', () => {
    const resp = { data: { id: 1, name: 'John Doe' } }
    mockAxios.get = jest.fn().mockResolvedValue(resp)
    return httpCall().then(res => expect(res).toEqual(resp.data))
  })
})

之后,我尝试将axios-mock代码移动到以下测试文件中

import axios from 'axios'
import httpCall from './index'
const mockAxios = jest.genMockFromModule('axios')

describe('mock module', () => {
  it('axios should be mocked', () => {
    const resp = { data: { id: 1, name: 'John Doe' } }
    mockAxios.get = jest.fn().mockResolvedValue(resp)
    return httpCall().then(res => expect(res).toEqual(resp.data))
  })
})

我再次遇到此错误

Request failed with status code 404

这是我的环境信息

System:
    OS: macOS 10.14
    CPU: (4) x64 Intel(R) Core(TM) i5-7360U CPU @ 2.30GHz
  Binaries:
    Node: 10.13.0 - ~/.nvm/versions/node/v10.13.0/bin/node
    Yarn: 1.7.0 - /usr/local/bin/yarn
    npm: 6.4.1 - ~/.nvm/versions/node/v10.13.0/bin/npm
  npmPackages:
    jest: ^23.6.0 => 23.6.0

我的.babelrc

{
  "presets": [
    [
      "@babel/env",
      {
        "modules": "umd"
      }
    ]
  ]
}

我的jest.config.js

module.exports = {

}

我希望有人能解释为什么会这样

jest mock module document确实有效吗?

1 个答案:

答案 0 :(得分:0)

现在可以正常工作了,问题是我的.babelrc文件

应该这样

{
  "presets": [
    [
      "@babel/env"
    ]
  ]
}

{
  "presets": [
    [
      "@babel/env",
      {
        "modules": "umd"
      }
    ]
  ],
  "env": {
    "test": {
      "presets": [
        [
          "@babel/env"
        ]
      ]
    }
  }
}