簡體   English   中英

使用Moxios模擬Axios調用以測試API調用

[英]Mocking Axios calls using Moxios in order to test API calls

我有以下自定義Axios實例:

import axios from 'axios'

export const BASE_URL = 'http://jsonplaceholder.typicode.com'

export default axios.create({
  baseURL: BASE_URL
})

有了相應的服務:

import http from './http'

export async function fetchUserPosts(id) {
  const reponse = await http.get(`/users/${id}/posts`)
  return reponse.data
}

這是對所述服務的測試:

import moxios from 'moxios'
import sinon from 'sinon'
import http from '@/api/http'
import { fetchUserPosts } from '@/api/usersService'

describe('users service', () => {
  beforeEach(() => {
    moxios.install(http)
  })

  afterEach(() => {
    moxios.uninstall(http)
  })

  it('fetches the posts of a given user', (done) => {
    const id = 1
    const expectedPosts = ['Post1', 'Post2']

    moxios.stubRequest(`/users/${id}/posts`, {
      status: 200,
      response: expectedPosts
    })

    const onFulfilled = sinon.spy()
    fetchUserPosts(1).then(onFulfilled)

    moxios.wait(() => {
      expect(onFulfilled.getCall(0).args[0].data).toBe(expectedPosts)
      done()
    })
  })
})

使用Karma + Jasmine執行時會引發以下錯誤:

Uncaught TypeError: Cannot read property 'args' of null thrown

我想測試的是,當端點/users/{id}/posts被點擊時,會發送一個模擬的響應。 這一切都在使用我的自定義axios實例http

我曾嘗試將存根作為moxios 節目文檔的第一個例子。 但是,我不認為這符合我的用例,因為我想檢查請求是否在我的服務中正確形成。

我也試過以下代碼,它按預期工作,但我想測試我的服務(以下代碼不執行 ):

import axios from 'axios'
import moxios from 'moxios'
import sinon from 'sinon'

describe('users service', () => {
  beforeEach(() => {
    moxios.install()
  })

  afterEach(() => {
    moxios.uninstall()
  })

  it('fetches the posts of a given user', (done) => {
    const id = 1
    const expectedPosts = ['Post1', 'Post2']

    moxios.stubRequest(`/users/${id}/posts`, {
      status: 200,
      response: expectedPosts
    })

    const onFulfilled = sinon.spy()
    axios.get(`/users/${id}/posts`).then(onFulfilled)

    moxios.wait(() => {
      expect(onFulfilled.getCall(0).args[0].data).toBe(expectedPosts)
      done()
    })
  })
})

關於如何修復錯誤的任何想法?

我知道這是一個古老的問題但是當我遇到同樣的問題時,我會發布我的方法:

在這種情況下你不需要使用sinon ,因為你有一個axios實例,用它來配置moxios (你已經做過)

beforeEach(() => {
    moxios.install(http)
  })
  afterEach(() => {
    moxios.uninstall(http)
})

然后你像這樣測試你的方法:

it('test get', async () => {
     const expectedPosts = ['Post1', 'Post2']

     moxios.wait(() => {
          const request = moxios.requests.mostRecent()
          request.respondWith({ status: 200, response: expectedPosts }) //mocked response
     })

     const result = await fetchUserPosts(1)
     console.log(result) // ['Post1','Post2'] 
     expect(result).toEqual(expectedPosts)
})

而已。

問候

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM