我看到一个类似的问题被问到 here ,但我不知道我只是不理解还是这是不同的情况?我有一个钩子(Hook),它公开了一个名为 fetchPeople
的函数调用函数search
这最终是我正在进行的 api 调用。我已经按照关于 mock 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.jsimport { searchPeople } from 'services/people'
const fetchPeople = async term => {
const { data } = await searchPeople({ term })
return formatPeople(data)
}
使用SearchPeople.test.jsimport 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
功能
最佳答案
如果我最初的问题不符合标准,我们深表歉意。我尽我所能 chop 最相关的信息,但意识到我可能遗漏了比我应该遗漏的更多的信息。好消息是我最终解决了我的问题。如果有人遇到同样的情况,这对我有用:
在我的 useSearchPeople.test.js
,我发现我可以模拟在我的 fetchPeople
中使用的我的 api 函数的实际导入。 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)
}
})
关于javascript - Jest - 模拟内部 axios API 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62942295/