diff --git a/__tests__/context/MessagesContext.test.tsx b/__tests__/context/MessagesContext.test.tsx new file mode 100644 index 00000000..37b6ad7e --- /dev/null +++ b/__tests__/context/MessagesContext.test.tsx @@ -0,0 +1,114 @@ +import React from 'react' +import { expect } from '@jest/globals' +import { act, render, screen } from '@testing-library/react' +import '@testing-library/jest-dom/jest-globals' + +import { + useMessagesContext, + MessagesProvider, +} from '../../src/context/MessagesContext' + +const TestComponent = () => { + const { messages, setMessages } = useMessagesContext() + + const handleAddMessage = () => { + setMessages([ + ...messages, + { + id: '1', + content: 'Hello World!', + sender: 'user1', + type: 'message', + timestamp: new Date().toUTCString(), + }, + ]) + } + + const handleClearMessage = () => { + setMessages([]) + } + + return ( +
+

+ Messages: {messages.map((message) => message.content).join(', ')} +

+

Messages Count: {messages.length}

+ + + +
+ ) +} + +describe('MessagesContext', () => { + it('provides the correct default values', () => { + render( + + + + ) + + expect(screen.getByTestId('messages')).toHaveTextContent(`Messages:`) + expect(screen.getByTestId('messagesCount')).toHaveTextContent( + `Messages Count: 0` + ) + }) + + it('allows adding messages in the context', () => { + render( + + + + ) + + const addMessageBtn = screen.getByText('Add Message') + + act(() => { + addMessageBtn.click() + }) + + expect(screen.getByTestId('messages')).toHaveTextContent( + `Messages: Hello World!` + ) + expect(screen.getByTestId('messagesCount')).toHaveTextContent( + `Messages Count: 1` + ) + + act(() => { + addMessageBtn.click() + }) + + expect(screen.getByTestId('messagesCount')).toHaveTextContent( + `Messages Count: 2` + ) + }) + + it('allows updating messages in the context', () => { + render( + + + + ) + + const clearMessageBtn = screen.getByText('Clear Message') + const addMessageBtn = screen.getByText('Add Message') + + act(() => { + clearMessageBtn.click() + }) + + expect(screen.getByTestId('messages')).toHaveTextContent(`Messages:`) + expect(screen.getByTestId('messagesCount')).toHaveTextContent( + `Messages Count: 0` + ) + + act(() => { + addMessageBtn.click() + }) + + expect(screen.getByTestId('messagesCount')).toHaveTextContent( + `Messages Count: 1` + ) + }) +})