[英]How to test a className with the Jest and React testing library
[英]How to test catch block in jest and react testing library while mocking API calls?
我有一個組件,其中 state 根據 API 調用的響應進行更新。 我能夠測試從 API 返回的數據是否正在屏幕上呈現。 但我不知道如何測試在 API 調用失敗時是否顯示了正確的消息(即 errorMessage)。
成分:
import React, { useState } from "react";
import { getTodos } from "./Api";
interface responseType {
completed: boolean;
id: number;
title: string;
userId: number;
}
const Todo: React.FC = () => {
const [isSuccess, set_isSuccess] = useState(false);
const [errorMessage, set_errorMessage] = useState('');
const [data, set_data] = useState<responseType[]>([]);
const handleFetchData = () => {
getTodos()
.then((response) => {
if (response) {
set_isSuccess(true);
set_data(response.slice(0, 4))
}
})
.catch((error) => {
console.log(error);
set_errorMessage('Failed to fetch data');
});
};
return (
<>
<h2>Demo App</h2>
<button onClick={handleFetchData}>Click</button>
<div>
{isSuccess ?
data.map((val) => val.title) : errorMessage}
</div>
</>
)
}
export default Todo;
在上面的代碼中, getTodos()
是用於調用 API 的 function。 當 API 調用成功時,我可以測試場景。 下面是測試文件。
import { render, screen, waitFor } from '@testing-library/react';
import Todo from './Todo';
import userEvent from '@testing-library/user-event';
jest.mock('./Api', () => ({
getTodos: jest.fn(() =>
Promise.resolve([
{
completed: false,
id: 1,
title: "a sample item",
userId: 1
}])
)
})
)
it('data fetched successfully', async () => {
render(<Todo />)
const btn = screen.getByRole('button', { name: 'Click' })
userEvent.click(btn);
await waitFor(() => screen.getByText(/a sample item/i));
})
我想在同一個文件中編寫一個類似的測試用例,以檢查當 API 調用失敗(捕獲塊被執行)時屏幕上是否呈現消息“無法獲取數據” 。
嘗試使用 promise.reject() 而不是 resolve() 來測試捕獲部分。
import Todo from './Todo';
import userEvent from '@testing-library/user-event';
jest.mock('./Api', () => ({
getTodos: jest.fn(() =>
Promise.reject(
{
message: "fetch failed"
})
)
})
)
it('data fetched successfully', async () => {
render(<Todo />)
const btn = screen.getByRole('button', { name: 'Click' })
userEvent.click(btn);
await waitFor(() => screen.getByText(/a sample item/i));
})```
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.