我正在尝试测试在几次相互交织的 API 调用(带有拦截器的 axios)之后返回响应对象的异步服务。现在我正在使用jest-mock-axios lib,但我对任何替代品或纯Jest持开放态度。
(我删除了不相关的代码部分,最初是用 TS 写的)
// services/persons.js
import personsAgent from '../agents/persons';
import places from './places';
[...]
const get = async ({ search = '', limit, offset }) => {
const places = await places.get({ search: '', limit: 1000, offset: 0 }); // api call to endpoint url '/places/'
const params = {
search: !!search.length ? search : null,
limit,
offset,
};
[...]
return personsAgent.getAll({ ...params }).then(resp => {
const results = sort(resp.data.results, .....).map((person, i) => {
const place = places?.data?.results.filter(.....);
return {
id: person.id,
name: person.first_name,
surname: person.last_name,
place,
};
});
return {
data: { ...resp.data, results },
status: resp.status,
};
});
};
[....]
export default {
get,
};
// agents/persons.js
import requests from '../utils/axios';
export default {
getAll: (params: object) => requests.get('/persons/', { params }),
}
// services/persons.test.js
import mockAxios from 'jest-mock-axios';
import persons from './persons';
afterEach(() => {
mockAxios.reset();
});
it('returns Persons data from API', async () => {
let catchFn = jest.fn(),
thenFn = jest.fn();
persons
.get({ search: '', limit: 10, offset: 0 })
.then(thenFn)
.catch(catchFn);
expect(mockAxios.get).toHaveBeenCalledWith('/persons/', {
params: { search: null, limit: 10, offset: 0 },
}); // FAIL - received: '/places/', { search: '', limit: 1000, offset: 0 }
let responseObj = {
data: {
results: ['test'],
},
};
mockAxios.mockResponse(responseObj);
expect(thenFn).toHaveBeenCalledWith({
data: {
results: ['test'],
},
status: 200,
});
expect(catchFn).not.toHaveBeenCalled();
});
我正在使用jest-mock-axios,而对于我的其他人来说,没有额外的内部调用的更简单的服务一切正常,但这是有问题的。如何忽略或嘲笑const places = await places.get()
专注于personsAgent.getAll()
?现在的问题是我正在测试请求const places = await places.get()
并且没有二次请求personsAgent.getAll()
。
axios.getReqByUrl('/persons/') // null
有什么想法、例子或替代方案吗?提前谢谢!