英文:
How to write test case for conditional statement
问题
以下是您提供的代码的中文翻译:
我有下面的条件语句,如何为条件运算符编写测试用例?
const SomeComponent = () => {
    return (
        <>
            {(usersApiSuccess && users.id !== null) ?
                <Dashboard />
                : (users.id === null) &&
                <ErrorPage content="用户不存在" />}
        </>
    )
}
英文:
I have below conditional statement, how I can write test case for conditional operator
const SomeComponent = () => {
    return (
        <>
            {(usersApiSuccess && users.id !== null) ?
                <Dashboard />
                : (users.id === null) &&
                <ErrorPage content="User does not exist" />}
        </>)
}
答案1
得分: 0
可以使用React Testing Library与Jest。
像这样
import { render } from '@testing-library/react';
describe('SomeComponent', () => {
  it('如果 usersApiSuccess 为 true 并且 users.id 不为 null,则渲染 Dashboard 组件', () => {
    const { getByTestId } = render(<SomeComponent usersApiSuccess={true} users={{ id: 1 }} />);
    expect(getByTestId('dashboard')).toBeInTheDocument();
  });
  it('如果 usersApiSuccess 为 true 并且 users.id 为 null,则渲染 ErrorPage 组件', () => {
    const { getByText } = render(<SomeComponent usersApiSuccess={true} users={{ id: null }} />);
    expect(getByText('User does not exist')).toBeInTheDocument();
  });
  it('如果 usersApiSuccess 为 false,则不渲染任何组件', () => {
    const { queryByTestId, queryByText } = render(<SomeComponent usersApiSuccess={false} users={{ id: 1 }} />);
    expect(queryByTestId('dashboard')).not.toBeInTheDocument();
    expect(queryByText('User does not exist')).not.toBeInTheDocument();
  });
});
[供参考][2]
英文:
You can use React Testing Library with Jest
Like this
import { render } from '@testing-library/react';
describe('SomeComponent', () => {
  it('renders the Dashboard component if usersApiSuccess is true and users.id is not null', () => {
    const { getByTestId } = render(<SomeComponent usersApiSuccess={true} users={{ id: 1 }} />);
    expect(getByTestId('dashboard')).toBeInTheDocument();
  });
  it('renders the ErrorPage component if usersApiSuccess is true and users.id is null', () => {
    const { getByText } = render(<SomeComponent usersApiSuccess={true} users={{ id: null }} />);
    expect(getByText('User does not exist')).toBeInTheDocument();
  });
  it('does not render any component if usersApiSuccess is false', () => {
    const { queryByTestId, queryByText } = render(<SomeComponent usersApiSuccess={false} users={{ id: 1 }} />);
    expect(queryByTestId('dashboard')).not.toBeInTheDocument();
    expect(queryByText('User does not exist')).not.toBeInTheDocument();
  });
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论