Jest.js 如何编写条件语句的测试用例

vwkv1x7d  于 2023-04-18  发布在  Jest
关注(0)|答案(1)|浏览(158)

我有下面的条件语句,我怎么能写测试用例的条件运算符

const SomeComponent = () => {
    return (
        <>
            {(usersApiSuccess && users.id !== null) ?
                <Dashboard />
                : (users.id === null) &&
                <ErrorPage content="User does not exist" />}
        </>)
}
z9smfwbn

z9smfwbn1#

您可以将React Testing LibraryJest一起使用
就像这样

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();
  });
});

For Reference

相关问题