Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 102 additions & 4 deletions src/components/Channel/__tests__/Channel.test.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React, { useEffect } from 'react';
import { fireEvent, render, waitFor } from '@testing-library/react';
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
import '@testing-library/jest-dom';

import { Channel } from '../Channel';
Expand All @@ -22,12 +22,16 @@ import {
threadRepliesApi,
useMockedApis,
} from '../../../mock-builders';
import { MessageList } from '../../MessageList';
import { Thread } from '../../Thread';

jest.mock('../../Loading', () => ({
LoadingErrorIndicator: jest.fn(() => <div />),
LoadingIndicator: jest.fn(() => <div>loading</div>),
}));

const MockAvatar = ({ user }) => <div className='avatar'>{user.custom}</div>;

let chatClient;
let channel;

Expand Down Expand Up @@ -63,12 +67,12 @@ const ActiveChannelSetter = ({ activeChannel }) => {
return null;
};

const user = generateUser({ id: 'id', name: 'name' });
const user = generateUser({ custom: 'custom-value', id: 'id', name: 'name' });

// create a full message state so we can properly test `loadMore`
const messages = [];
for (let i = 0; i < 25; i++) {
messages.push(generateMessage());
messages.push(generateMessage({ user }));
}

const pinnedMessages = [generateMessage({ pinned: true, user })];
Expand Down Expand Up @@ -110,7 +114,7 @@ describe('Channel', () => {
});

it('should render the EmptyPlaceholder prop if the channel is not provided by the ChatContext', () => {
const { getByText } = render(<Channel EmptyPlaceholder={<div>empty</div>}></Channel>);
const { getByText } = render(<Channel EmptyPlaceholder={<div>empty</div>} />);

expect(getByText('empty')).toBeInTheDocument();
});
Expand Down Expand Up @@ -741,6 +745,100 @@ describe('Channel', () => {

await waitFor(() => expect(newThreadMessageWasAdded).toBe(true));
});

it('should update user data in MessageList based on updated_at', async () => {
const updatedAttribute = { custom: 'newCustomValue' };
const dispatchUserUpdatedEvent = createChannelEventDispatcher(
{
user: { ...user, ...updatedAttribute, updated_at: new Date().toISOString() },
},
'user.updated',
);
renderComponent({ Avatar: MockAvatar, children: <MessageList /> });

await waitFor(() =>
expect(screen.queryByText(updatedAttribute.custom)).not.toBeInTheDocument(),
);
act(() => {
dispatchUserUpdatedEvent();
});
await waitFor(() =>
expect(screen.queryAllByText(updatedAttribute.custom).length).toBeGreaterThan(0),
);
});

it('should not update user data in MessageList if updated_at has not changed', async () => {
const updatedAttribute = { custom: 'newCustomValue' };
const dispatchUserUpdatedEvent = createChannelEventDispatcher(
{
user: { ...user, ...updatedAttribute },
},
'user.updated',
);
renderComponent({ Avatar: MockAvatar, children: <MessageList /> });

await waitFor(() =>
expect(screen.queryByText(updatedAttribute.custom)).not.toBeInTheDocument(),
);
act(() => {
dispatchUserUpdatedEvent();
});
await waitFor(() =>
expect(screen.queryByText(updatedAttribute.custom)).not.toBeInTheDocument(),
);
});

it('should update user data in Thread if updated_at has changed', async () => {
const threadMessage = messages[0];
const updatedAttribute = { custom: 'newCustomValue' };
const dispatchUserUpdatedEvent = createChannelEventDispatcher(
{
user: { ...user, ...updatedAttribute, updated_at: new Date().toISOString() },
},
'user.updated',
);
renderComponent({ Avatar: MockAvatar, children: <Thread /> }, ({ openThread, thread }) => {
if (!thread) {
openThread(threadMessage, { preventDefault: () => null });
}
});

await waitFor(() =>
expect(screen.queryByText(updatedAttribute.custom)).not.toBeInTheDocument(),
);
act(() => {
dispatchUserUpdatedEvent();
});
await waitFor(() =>
expect(screen.queryAllByText(updatedAttribute.custom).length).toBeGreaterThan(0),
);
});

it('should not update user data in Thread if updated_at has not changed', async () => {
const threadMessage = messages[0];
const updatedAttribute = { custom: 'newCustomValue' };
const dispatchUserUpdatedEvent = createChannelEventDispatcher(
{
user: { ...user, ...updatedAttribute },
},
'user.updated',
);
renderComponent({ Avatar: MockAvatar, children: <Thread /> }, ({ openThread, thread }) => {
if (!thread) {
openThread(threadMessage, { preventDefault: () => null });
}
});

await waitFor(() =>
expect(screen.queryByText(updatedAttribute.custom)).not.toBeInTheDocument(),
);
act(() => {
dispatchUserUpdatedEvent();
});
await waitFor(() =>
expect(screen.queryByText(updatedAttribute.custom)).not.toBeInTheDocument(),
);
});
});
});
});
4 changes: 2 additions & 2 deletions src/components/Channel/hooks/useCreateChannelStateContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ export const useCreateChannelStateContext = <
updated_at && (isDayOrMoment(updated_at) || isDate(updated_at))
? updated_at.toISOString()
: updated_at || ''
}${user?.image}${user?.name}`,
}${user?.updated_at}`,
)
.join();

Expand All @@ -86,7 +86,7 @@ export const useCreateChannelStateContext = <
updated_at && (isDayOrMoment(updated_at) || isDate(updated_at))
? updated_at.toISOString()
: updated_at || ''
}${user?.image}${user?.name}`,
}${user?.updated_at}`,
)
.join();

Expand Down
23 changes: 20 additions & 3 deletions src/components/ChannelPreview/ChannelPreview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,11 +58,12 @@ export const ChannelPreview = <
props: ChannelPreviewProps<StreamChatGenerics>,
) => {
const { channel, Preview = ChannelPreviewMessenger, channelUpdateCount } = props;

const { channel: activeChannel, client, setActiveChannel } = useChatContext<StreamChatGenerics>(
'ChannelPreview',
);
const { t, userLanguage } = useTranslationContext('ChannelPreview');
const [displayTitle, setDisplayTitle] = useState(getDisplayTitle(channel, client.user));
const [displayImage, setDisplayImage] = useState(getDisplayImage(channel, client.user));

const [lastMessage, setLastMessage] = useState<StreamMessage<StreamChatGenerics>>(
channel.state.messages[channel.state.messages.length - 1],
Expand Down Expand Up @@ -109,10 +110,26 @@ export const ChannelPreview = <
};
}, [refreshUnreadCount, channelUpdateCount]);

useEffect(() => {
const handleEvent = () => {
setDisplayTitle((displayTitle) => {
const newDisplayTitle = getDisplayTitle(channel, client.user);
return displayTitle !== newDisplayTitle ? newDisplayTitle : displayTitle;
});
setDisplayImage((displayImage) => {
const newDisplayImage = getDisplayImage(channel, client.user);
return displayImage !== newDisplayImage ? newDisplayImage : displayImage;
});
};

client.on('user.updated', handleEvent);
return () => {
client.off('user.updated', handleEvent);
};
}, []);

if (!Preview) return null;

const displayImage = getDisplayImage(channel, client.user);
const displayTitle = getDisplayTitle(channel, client.user);
const latestMessage = getLatestMessagePreview(channel, t, userLanguage);

return (
Expand Down
114 changes: 109 additions & 5 deletions src/components/ChannelPreview/__tests__/ChannelPreview.test.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,27 @@
import React from 'react';
import { act, render, waitFor } from '@testing-library/react';
import { act, render, screen, waitFor } from '@testing-library/react';
import '@testing-library/jest-dom';

import { ChannelPreview } from '../ChannelPreview';
import { Chat } from '../../Chat';

import { ChatContext } from '../../../context/ChatContext';

import {
dispatchMessageDeletedEvent,
dispatchMessageNewEvent,
dispatchMessageUpdatedEvent,
dispatchUserUpdatedEvent,
generateChannel,
generateMember,
generateMessage,
generateUser,
getRandomInt,
getTestClientWithUser,
queryChannelsApi,
useMockedApis,
} from 'mock-builders';

import { ChatContext } from '../../../context';
import { ChannelPreview } from '../ChannelPreview';

const PreviewUIComponent = (props) => (
<>
<div data-testid='channel-id'>{props.channel.id}</div>
Expand Down Expand Up @@ -131,7 +136,7 @@ describe('ChannelPreview', () => {

const { getByTestId } = renderComponent(
{
activeChannel: c1,
activteChannel: c1,
channel: c0,
},
render,
Expand Down Expand Up @@ -218,4 +223,103 @@ describe('ChannelPreview', () => {
await expectUnreadCountToBe(getByTestId, 0);
});
});

describe('user.updated', () => {
let chatClient;
let channels;
let channelState;
let otherUser;
const MockAvatar = ({ image, name }) => (
<>
<div className='avatar-name'>{name}</div>
<div className='avatar-image'>{image}</div>
</>
);

const channelPreviewProps = {
Avatar: MockAvatar,
};

beforeEach(async () => {
const activeUser = generateUser({
custom: 'custom1',
id: 'id1',
image: 'image1',
name: 'name1',
});
otherUser = generateUser({
custom: 'custom2',
id: 'id2',
image: 'image2',
name: 'name2',
});
channelState = generateChannel({
members: [generateMember({ user: activeUser }), generateMember({ user: otherUser })],
messages: [generateMessage({ user: activeUser }), generateMessage({ user: otherUser })],
});
chatClient = await getTestClientWithUser(activeUser);
useMockedApis(chatClient, [queryChannelsApi([channelState])]);
channels = await chatClient.queryChannels();
});

it("should update the direct messaging channel's preview if other user's name has changed", async () => {
const updatedAttribute = { name: 'new-name' };
const channel = channels[0];
render(
<Chat client={chatClient}>
<ChannelPreview {...channelPreviewProps} channel={channel} />
</Chat>,
);

await waitFor(() =>
expect(screen.queryByText(updatedAttribute.name)).not.toBeInTheDocument(),
);
act(() => {
dispatchUserUpdatedEvent(chatClient, { ...otherUser, ...updatedAttribute });
});
await waitFor(() =>
expect(screen.queryAllByText(updatedAttribute.name).length).toBeGreaterThan(0),
);
});

it("should update the direct messaging channel's preview if other user's image has changed", async () => {
const updatedAttribute = { image: 'new-image' };
const channel = channels[0];
render(
<Chat client={chatClient}>
<ChannelPreview {...channelPreviewProps} channel={channel} />
</Chat>,
);

await waitFor(() =>
expect(screen.queryByText(updatedAttribute.image)).not.toBeInTheDocument(),
);
act(() => {
dispatchUserUpdatedEvent(chatClient, { ...otherUser, ...updatedAttribute });
});
await waitFor(() =>
expect(screen.queryAllByText(updatedAttribute.image).length).toBeGreaterThan(0),
);
});

it("should not update the direct messaging channel's preview if other user attribute than name or image has changed", async () => {
const updatedAttribute = { custom: 'new-custom' };
const channel = channels[0];
render(
<Chat client={chatClient}>
<ChannelPreview {...channelPreviewProps} channel={channel} />
</Chat>,
);

await waitFor(() =>
expect(screen.queryByText(updatedAttribute.custom)).not.toBeInTheDocument(),
);
act(() => {
dispatchUserUpdatedEvent(chatClient, { ...otherUser, ...updatedAttribute });
});
await waitFor(() =>
expect(screen.queryByText(updatedAttribute.custom)).not.toBeInTheDocument(),
);
});
});
});
13 changes: 4 additions & 9 deletions src/components/Message/utils.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -246,8 +246,7 @@ export const areMessagePropsEqual = <
prevMessage.text === nextMessage.text &&
prevMessage.type === nextMessage.type &&
prevMessage.updated_at === nextMessage.updated_at &&
prevMessage.user?.image === nextMessage.user?.image &&
prevMessage.user?.name === nextMessage.user?.name;
prevMessage.user?.updated_at === nextMessage.user?.updated_at;

if (!messagesAreEqual) return false;

Expand Down Expand Up @@ -295,7 +294,7 @@ export const areMessageUIPropsEqual = <
return false;
}

const messagesAreEqual =
return (
prevMessage.deleted_at === nextMessage.deleted_at &&
prevMessage.latest_reactions?.length === nextMessage.latest_reactions?.length &&
prevMessage.own_reactions?.length === nextMessage.own_reactions?.length &&
Expand All @@ -305,12 +304,8 @@ export const areMessageUIPropsEqual = <
prevMessage.text === nextMessage.text &&
prevMessage.type === nextMessage.type &&
prevMessage.updated_at === nextMessage.updated_at &&
prevMessage.user?.image === nextMessage.user?.image &&
prevMessage.user?.name === nextMessage.user?.name;

if (!messagesAreEqual) return false;

return true;
prevMessage.user?.updated_at === nextMessage.user?.updated_at
);
};

export const messageHasReactions = <
Expand Down
1 change: 1 addition & 0 deletions src/mock-builders/event/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,4 @@ export { default as dispatchNotificationAddedToChannelEvent } from './notificati
export { default as dispatchNotificationMessageNewEvent } from './notificationMessageNew';
export { default as dispatchNotificationMutesUpdated } from './notificationMutesUpdated';
export { default as dispatchNotificationRemovedFromChannel } from './notificationRemovedFromChannel';
export { default as dispatchUserUpdatedEvent } from './userUpdated';
Loading