我正在尝试理解这个例子,所以我尝试的第一件事是移除他的AxiosConfig.js
,所以这个例子看起来更像是我想要解决的当前案例。但是我得到了这个错误
- Expected
+ Received
Object {
+ "baseURL": "https://jsonplaceholder.typicode.com/albums",
"method": "get",
"url": "/3/photos?_limit=3",
},
Number of calls: 1
39 | const photos = await getPhotosByAlbumID(3);
40 | expect(axios.request).toHaveBeenCalled();
> 41 | expect(axios.request).toHaveBeenCalledWith({ method: 'get', url: '/3/photos?_limit=3' })
| ^
42 | expect(photos.length).toEqual(3);
43 | expect(photos[0].albumId).toEqual(3)
44 | });
有人能想出如何修复失败的测试吗?
如果我从GetPhotosByAlbumid()
中删除Baseurl:'https://jsonPlaceholder.typicode.com/Albums'
,但如果没有Baseurl
,则没有任何意义。
我在https://repl./@sandraschlichti/jest-playground#index.js上找到了它
index.js
const axios = require('axios');
const getPhotosByAlbumId = async (id) => {
const result = await axios.request({
baseURL: 'https://jsonplaceholder.typicode.com/albums',
method: 'get',
url: `/${id}/photos?_limit=3`
});
const { data } = result;
return data;
};
module.exports = getPhotosByAlbumId;
index.spec.js
const axios = require('axios');
const getPhotosByAlbumID = require('./index');
jest.mock('axios', () => {
return {
baseURL: 'https://jsonplaceholder.typicode.com/albums',
request: jest.fn().mockResolvedValue({
data: [
{
albumId: 3,
id: 101,
title: 'incidunt alias vel enim',
url: 'https://via.placeholder.com/600/e743b',
thumbnailUrl: 'https://via.placeholder.com/150/e743b'
},
{
albumId: 3,
id: 102,
title: 'eaque iste corporis tempora vero distinctio consequuntur nisi nesciunt',
url: 'https://via.placeholder.com/600/a393af',
thumbnailUrl: 'https://via.placeholder.com/150/a393af'
},
{
albumId: 3,
id: 103,
title: 'et eius nisi in ut reprehenderit labore eum',
url: 'https://via.placeholder.com/600/35cedf',
thumbnailUrl: 'https://via.placeholder.com/150/35cedf'
}
]
})
}
})
describe('test getPhotosByAlbumID ', () => {
afterEach(() => jest.resetAllMocks());
it('fetches photos by album id', async () => {
const photos = await getPhotosByAlbumID(3);
expect(axios.request).toHaveBeenCalled();
expect(axios.request).toHaveBeenCalledWith({ method: 'get', url: '/3/photos?_limit=3' })
expect(photos.length).toEqual(3);
expect(photos[0].albumId).toEqual(3)
});
});
由于在您的实现中使用具有baseURL的对象调用Axios.Request
,因此它与您的断言不匹配。
因此您可以断言必须使用具有baseURL的对象调用它
expect(axios.request).toHaveBeenCalledWith({
baseURL: "https://jsonplaceholder.typicode.com/albums",
method: "get",
url: "/3/photos?_limit=3",
});
或者调用该方法的对象必须具有以下两个属性:
expect(axios.request).toHaveBeenCalledWith(
expect.objectContaining({ method: "get", url: "/3/photos?_limit=3" })
);
工作示例
我建议你使用非对称匹配器
expect(axios.request).toHaveBeenCalledWith(
expect.objectContaining({
method: 'get',
url: '/3/photos?_limit=3'
}))
有时你有一个大的对象,没有必要匹配确切的对象,你可以选择哪些你想要比较的对象。
另一个例子可以是:
expect(mock).toHaveBeenCalledWith(expect.objectContaining({
postalCode: expect.any(Number)
}));
下面是运行https://repl.it/join/ldayfmqz-yoandrycollazo的示例