Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to write a test with Jest and React testing library to check if anchor-tag <a /> exist

Based on a prop anchor I am rendering a Material ui button or a React router (anchor) link:

const Button = (props: Props) => {

  return props.anchor ? (
    <Link to={props.url!}>
        {props.children}
    </Link>
  ) : (
    <MaterialButton
      onClick={props.onClick}
    >
      {props.children}
    </MaterialButton>
  );
};

How do I write a test with Jest and React testing library to check if anchor-tag <a /> exist in my test:

describe('Button', () => {
  const mount = (tree: ReactElement) => new FixtureMount(tree).withTheme().render();
  it('should render correctly', () => {
    const { container } = mount(<Button>Test</Button>);
    expect(container).toMatchSnapshot();
  });

  it('should render anchor button', () => {
    const { container } = mount(<Button anchorButton>Test</Button>);
    expect(// ----> What to add here?);
  });
});

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

it('should render anchor button', () => {
    const { container } = mount(<Button anchorButton>Test</Button>);
    expect(container.getByText('Test').closest('a')).toBeInTheDocument()
  });
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading