簡體   English   中英

笑話 - 模擬內部 axios API 調用

[英]Jest - Mock Inner axios API Call

我在這里看到了一個類似的問題,但我不知道我是否只是不理解,或者這是一個不同的情況? 我有一個鈎子,它暴露了一個名為fetchPeople的 function ,它調用了一個 function search ,這最終是我正在制作的 api 調用。 我已經按照關於 mocking axios的笑話的示例進行了操作,但似乎我的測試仍然(可能)使物理 api 調用而不返回我的解析模擬值。 通過調試,我意識到響應是這樣的:

baseURL: "mock.api.imirwin.com"
headers: {}
responseType: "json"
__proto__: Object

這是我的代碼的結構:

服務/people.js

async function search(params) {
 const response = await axios.get(url)

 return {
  data: response.data,
  links: response.links,
  count: response.count,
 }
}

使用SearchPeople.js

import { searchPeople } from 'services/people'

const fetchPeople = async term => {
 const { data } = await searchPeople({ term })

 return formatPeople(data)
}

使用SearchPeople.test.js

import useSearchPeople from './useSearchPeople'
import axios from 'axios'

const { fetchPeople } = useSearchPeople()

jest.mock('axios')

describe('useSearchPeople', () => {
 it('returns an array of people', async () => {
  axios.get.mockResolvedValue(response)
  const data = await fetchPeople('term')
 )}
}

我從中得到的錯誤是:

    TypeError: Cannot read property 'total' of undefined

      138 |     data: deserializerAndCase().deserialize(response),
      139 |     links: response.links,
    > 140 |     count: response.meta.total,
          |                          ^
      141 |   }
      142 | }

我理解這意味着正在調用 api,但未返回模擬響應。

從擺弄中,我注意到如果我模擬我的服務jest.mock('services/people') ,它不會進行物理調用,但是仍然沒有返回模擬的響應,而是我得到了這個錯誤

    TypeError: Cannot destructure property `data` of 'undefined' or 'null'.
      32 | const fetchPeople = async term => {
    > 33 |   const { data } = await searchPeople({ term })
         |         ^
      34 |   return formatPeople(data)
      35 | }
      36 | 

任何見解將不勝感激。 編輯:我應該補充一點,我最終要測試的是formatPeople function

如果我最初的問題不符合標准,我們深表歉意。 我盡我所能截斷最相關的信息,但意識到我可能遺漏了比我應該遺漏的更多的信息。 好消息是我最終解決了我的問題。 如果有人遇到同樣的情況,這對我有用:

在我的useSearchPeople.test.js中,我發現我可以模擬我的 api function 的實際導入,該導入在我的fetchPeople useSearchPeople.js中使用。 我所做的是這樣的:

使用SearchPeople.test.js

import { useSearchPeople } from './useSearchPeople'
import { searchPeople } from 'services/people'

const response = { data: [{}] }
const { fetchPeople } = useSearchPeople()

jest.mock('services/people', () => {
 return {
   search: jest.fn().mockReturnValue(response)
 }
})

describe('useSearchPeople hook', () => {
 it('returns data from external api call', async () => {
  const data = await fetchPeople('something')

  expect(data.length).toBe(1)
 }
})

暫無
暫無

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

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