Skip to content

Instantly share code, notes, and snippets.

@makomweb
Last active May 12, 2023 14:33
Show Gist options
  • Save makomweb/b68b15ec7ba0fb6feb16d4608e41dba7 to your computer and use it in GitHub Desktop.
Save makomweb/b68b15ec7ba0fb6feb16d4608e41dba7 to your computer and use it in GitHub Desktop.
Test a React component via React-Testing-Library
// HiddenMessage.tsx
import * as React from "react";

function HiddenMessage({children}) {
    const [showMessage, setShowMessage] = React.useState(false)
    return (
        <div>
            <label htmlFor="toggle">Show Message</label>
            <input
                id="toggle"
                type="checkbox"
                onChange={e => setShowMessage(e.target.checked)}
                checked={showMessage}
            />
            {showMessage ? children : null}
        </div>
    )
}

export default HiddenMessage;
// HiddenMessage.test.tsx
import React from 'react';
import '@testing-library/jest-dom'
import {render, fireEvent, screen} from '@testing-library/react'
import HiddenMessage from './HiddenMessage'

test('shows the children when the checkbox is checked', () => {
    const testMessage = 'Test Message'
    render(<HiddenMessage>{testMessage}</HiddenMessage>)

    // query* functions will return the element or null if it cannot be found
    // get* functions will return the element or throw an error if it cannot be found
    expect(screen.queryByText(testMessage)).toBeNull()

    // the queries can accept a regex to make your selectors more resilient to content tweaks and changes.
    fireEvent.click(screen.getByLabelText(/show/i))

    // .toBeInTheDocument() is an assertion that comes from jest-dom
    // otherwise you could use .toBeDefined()
    expect(screen.getByText(testMessage)).toBeInTheDocument()
})
dev@ea7f4f56b2ed:/sandbox$ npm test --testFile "HiddenMessage"

> test
> jest --detectOpenHandles HiddenMessage

 PASS  assets/js/Sandbox/HiddenMessage.test.tsx (5.513 s)
  ✓ shows the children when the checkbox is checked (50 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        5.879 s
Ran all test suites matching /HiddenMessage/i.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment