使用基于 API 响应的 useState 钩子来测试条件渲染

问题描述 投票:0回答:1

我有这个 React 组件,它有一个基于 API 响应呈现的块。

const SomeComponent = () => {

const [render, setRender] = useState(false)

const handleClick = async () => {
  const someFunction = await callToAPI()
    if (someFunction) {
      setRender(true)
    }
}

return (
  <main>
    <button onClick={handleClick}></button>
    <ShouldRender when={render} data-test-id='should-render'>
      Something
    </ShouldRender>
  </main>
  )
}

当我为其编写测试时,我对如何测试此条件渲染感到困惑。 我想知道是否有办法使用

fireEvent
之类的东西在我的
SomeComponent.test.js
文件中设置此状态。

到目前为止,测试看起来像这样:

test('renders component when button is clicked', () => {
  render(<SomeComponent />)
  const button = screen.queryByRole('button')
  fireEvent.click(button)
  const conditionalComponent = screen.getByTestId('should-render')
  expect(conditionalComponent).toBeInTheDocument()
})
javascript reactjs testing jestjs
1个回答
0
投票

您可以使用https://mock-api.net之类的工具来模拟API响应。以下是如何修改测试以使用在线模拟工具的示例:

// Import necessary testing libraries
import { render, screen, fireEvent } from '@testing-library/react';
import SomeComponent from './SomeComponent';

// Your test
test('renders component when button is clicked', async () => {
  // Define the mock API endpoint from MockAPI
  const mockApiEndpoint = 'https://mockapi.io/api/demo/testcomponent';

  // Mock the fetch function to intercept API requests
  jest.spyOn(global, 'fetch').mockResolvedValue({
    json: async () => ({ /* Your mocked API response here */ }),
  });

  // Render the component
  render(<SomeComponent />);

  // Find and click the button
  const button = screen.getByRole('button');
  fireEvent.click(button);

  // Wait for the component to render based on the mocked API response
  await screen.findByTestId('should-render');

  // Assert that the conditional component is in the document
  const conditionalComponent = screen.getByTestId('should-render');
  expect(conditionalComponent).toBeInTheDocument();

  // Restore the original fetch function after the test
  global.fetch.mockRestore();
});

在这个例子中,我们使用jest.spyOn来模拟fetch函数并拦截对MockAPI的API请求。然后使用 json 函数来模拟 API 响应。

请将 /* 此处的模拟 API 响应 */ 替换为您从给定端点的 MockAPI 获得的 API 响应的预期结构。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.