Can I test if a component

I have a react component that looks like this. I’m writing a test for the component.

const Button = ({text, type}) => {
  return (
    <div>
      <button aria-label={text} className={`Button`} type={type}>
        {text}
      </button>   
    </div> 
  )
}

How can I test so that when I add the prop, “type=’submit'”, I verify that a SubmitEvent fires? The onSubmit handler is attached to another react component called Form that lies outside of the Button and is something I want to test independently in another test for the Form.

Answer

You can create a simple form component to wrap the Button component in the test case. Use fireEvent.click(button) to trigger the submit event. Verify if the submit is triggered or not.

index.tsx:

import React from "react"

export const Button = ({ text, type }) => {
    return (
        <div>
            <button aria-label={text} className={`Button`} type={type}>
                {text}
            </button>
        </div>
    )
}

index.test.tsx:

import { screen, render, fireEvent } from '@testing-library/react'
import React from 'react'
import { Button } from './'

describe('69029886', () => {
    test('should pass', () => {
        const onSubmit = jest.fn(e => e.preventDefault());
        render(<Button type='submit' text='submit' />, { wrapper: ({ children }) => <form onSubmit={onSubmit}>{children}</form> })
        const button = screen.getByLabelText(/submit/)
        fireEvent.click(button)
        expect(onSubmit).toBeCalled();
    })
})

test result:

 PASS  examples/69029886/index.test.tsx (9.386 s)
  69029886
    ✓ should pass (29 ms)

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
-----------|---------|----------|---------|---------|-------------------
All files  |     100 |      100 |     100 |     100 |                   
 index.tsx |     100 |      100 |     100 |     100 |                   
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        9.95 s