我看到了一个类似的问题here,但我不知道我是否只是不理解,或者是否是另外一种情况?我有一个钩子,暴露了一个名为fetchPeople
的函数,该函数调用了一个函数search
,该函数最终就是我正在进行的api调用。我开玩笑地讲过关于模拟axios
的示例,但是看来我的测试仍然是(也许)进行物理api调用,而不返回我解析的模拟值。通过调试,我意识到响应是这样的:
baseURL: "mock.api.imirwin.com"
headers: {}
responseType: "json"
__proto__: Object
这是我的代码的结构:
services / people.js
async function search(params) {
const response = await axios.get(url)
return {
data: response.data,
links: response.links,
count: response.count,
}
}
useSearchPeople.js
import { searchPeople } from 'services/people'
const fetchPeople = async term => {
const { data } = await searchPeople({ term })
return formatPeople(data)
}
useSearchPeople.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
函数
答案 0 :(得分:2)
很抱歉,如果我最初提出的问题不符合标准。我竭尽所能截断最相关的信息,但意识到我可能遗漏了过多的内容。好消息是我最终解决了我的问题。如果有人遇到相同的情况,这对我有用:
在我的useSearchPeople.test.js
中,我发现可以模拟fetchPeople
钩子中useSearchPeople.js
函数中使用的api函数的实际导入。我所做的是这样:
useSearchPeople.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)
}
})