Add another example

This commit is contained in:
Steve Kinney
2024-10-01 19:36:39 -05:00
parent 867bc939ae
commit 5710f74461
5 changed files with 58 additions and 3 deletions

View File

@@ -0,0 +1,20 @@
import { useState } from 'react';
export const AlertButton = ({}) => {
const [message, setMessage] = useState('Alert!');
return (
<div>
<label>
Message
<input
type="text"
value={message}
onChange={(event) => setMessage(event.target.value)}
/>
</label>
<button onClick={() => alert(message)}>Trigger Alert</button>
</div>
);
};

View File

@@ -0,0 +1,34 @@
import { render, screen, act } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { AlertButton } from './alert-button';
describe('AlertButton', () => {
beforeEach(() => {
vi.spyOn(window, 'alert').mockImplementation(() => {});
render(<AlertButton />);
});
afterEach(() => {
vi.restoreAllMocks();
});
it('should render an alert button', async () => {
const button = screen.getByRole('button', { name: /trigger alert/i });
expect(button).toBeInTheDocument();
});
it('should trigger an alert', async () => {
const button = screen.getByRole('button', { name: /trigger alert/i });
const messageInput = screen.getByLabelText(/message/i);
await act(async () => {
await userEvent.clear(messageInput);
await userEvent.type(messageInput, 'Hello, world!');
await userEvent.click(button);
});
expect(window.alert).toHaveBeenCalledWith('Hello, world!');
});
});