使用moxios模拟通话时遇到麻烦

时间:2019-03-16 01:39:08

标签: unit-testing axios moxios

我有一个默认的axios实例,并安装了该测试:

// http.js
import Axios from 'axios'

export const instance = Axios.create({
  baseURL: 'https://cs-node-123.herokuapp.com'
})

我将其导入正在测试的服务和测试中:

// RatingsService.js
import { instance } from '@/http'
import RatingsFactory from '@/models/Ratings/RatingsFactory'
import config from '@/utils/config'

const endpoint = 'api/rac/v1/ratings'

export default class RatingsService {

  static async hasRated(objGuid) {
    try {
      const result = await instance.get(endpoint, {
        params: {
          obj_guid: objGuid,
          user_guid: config.store.state.auth.user.userId
        }
      })
      return RatingsFactory(result.data)
    } catch (error) {
      throw error
    }
  }

  ...
}
// RatingsService.spec.js
import RatingsService from '../RatingsService'
import { instance } from '@/http'
import moxios from 'moxios'

describe('RatingsService.js', () => {
  beforeEach(() => {
    moxios.install(instance)
  })
  afterEach(() => {
    moxios.uninstall(instance)
  })

  it('handles the call to hasRated', async () => {
    moxios.wait(() => {
      const request = moxios.requests.mostRecent()
      console.log(request)
      request.respondWith({
        status: 200,
        response: {}
      })
    })
    await RatingsService.hasRated('123')
    expect(1).toBe(2)
  })
})

代码调用并执行该请求,由于某些原因,moxios不会接收它。我也尝试仅将axios传递给moxios.install(axios),但这也不起作用。我还在instance.defaults.adapter之前将axios.defaults.adapter设置为moxios.install(instance),但这也没有用...

感谢您的帮助。

0 个答案:

没有答案