将以下代码放入我的test.tsx文件中。
test('Photos will load', async () => {
const mockCuratedPhotos = jest.spyOn(endpoints, 'getCuratedPhotos');
mockCuratedPhotos.mockResolvedValue(mockPhotos);
await render(<Home />)
let element = screen.getByText('Home');
let search = screen.getByTestId('search')
expect(element).toBeInTheDocument();
expect(search).toBeInTheDocument();
})
我尝试在Next.js应用中使用jest和React Testing Library编写测试。我正在模拟API调用,以便组件加载mockPhotos,但我可以看到测试中未加载数据。Typescript编译器引发以下错误:Argument of type 'Photos[]' is not assignable to parameter of type 'Photos | ErrorResponse | Promise<Photos | ErrorResponse | undefined> | undefined'.ts(2345)
我的模拟数据实际上是从实际的API GET调用中提取的一个片段,所以我知道它的格式是准确的。为什么Typescript会抱怨呢?我认为当我使用mockResolvedValue()
时,组件只是假设接受这是它将接收的数据。
//实际API函数
export const getCuratedPhotos = async (page?: number) => {
const client = createClient(key);
try {
if (!page) {
return await client.photos.curated({ per_page: 10 });
} else {
return await client.photos.curated({ per_page: 10, page });
}
} catch (e) {
console.log('error', e);
}
}
//模拟常量
export const mockPhotos: Array<Photos> = [
{
"page": 1,
"per_page": 10,
"photos": [
{
"id": 15823317,
"width": 4043,
"height": 6064,
"url": "https://www.pexels.com/photo/love-summer-sun-leaf-15823317/",
"photographer": "Mathilde Langevin",
"photographer_url": "https://www.pexels.com/@mathilde",
"photographer_id": 157994802,
"avg_color": "#9B9887",
"src": {
"original": "https://images.pexels.com/photos/15823317/pexels-photo-15823317.jpeg",
"large2x": "https://images.pexels.com/photos/15823317/pexels-photo-15823317.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940",
"large": "https://images.pexels.com/photos/15823317/pexels-photo-15823317.jpeg?auto=compress&cs=tinysrgb&h=650&w=940",
"medium": "https://images.pexels.com/photos/15823317/pexels-photo-15823317.jpeg?auto=compress&cs=tinysrgb&h=350",
"small": "https://images.pexels.com/photos/15823317/pexels-photo-15823317.jpeg?auto=compress&cs=tinysrgb&h=130",
"portrait": "https://images.pexels.com/photos/15823317/pexels-photo-15823317.jpeg?auto=compress&cs=tinysrgb&fit=crop&h=1200&w=800",
"landscape": "https://images.pexels.com/photos/15823317/pexels-photo-15823317.jpeg?auto=compress&cs=tinysrgb&fit=crop&h=627&w=1200",
"tiny": "https://images.pexels.com/photos/15823317/pexels-photo-15823317.jpeg?auto=compress&cs=tinysrgb&dpr=1&fit=crop&h=200&w=280"
},
"liked": false,
"alt": ""
},
{
etc...
}
],
"total_results": 8000,
"next_page": "https://api.pexels.com/v1/curated/?page=3&per_page=10",
"prev_page": "https://api.pexels.com/v1/curated/?page=1&per_page=10"
}
]
1条答案
按热度按时间lndjwyie1#
我想你可能误解了API的响应,我猜你用的是这个API:https://www.pexels.com/api/documentation/?language=javascript#photos-curated
如果这是真的,您可以看到响应总是只包含一次一个页面。如果您想获得更多页面,您可以使用
next_page
值发出另一个请求。在您的例子中,这意味着您应该使用
Photos
类型而不是Array<Photos>
作为mockedPhotos
变量,如下所示:因此,正如您所看到的,一次只有一个页面,
page
键表示当前页面,photos
数组表示实际的照片。API不返回页面数组-一次只返回一个页面。