Skip to content

Commit 82a93b4

Browse files
authored
Add minor util tests (#1294)
### Changelog * Added minor test cases for util functions * Removed unused util functions
1 parent 2c0387f commit 82a93b4

File tree

7 files changed

+141
-75
lines changed

7 files changed

+141
-75
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import { cloneMessage } from '../cloneMessage';
2+
3+
describe('cloneMessage', () => {
4+
it('Should return a clone message', () => {
5+
const oldMessage = {
6+
isAdminMessage: true,
7+
isUserMessage: true,
8+
isFileMessage: true,
9+
isMultipleFilesMessage: true,
10+
applyParentMessage: true,
11+
applyReactionEvent: true,
12+
applyThreadInfoUpdateEvent: true,
13+
extraProps: {
14+
field1: true,
15+
field2: 'test',
16+
field3: 42,
17+
},
18+
};
19+
20+
const newMessage = cloneMessage(oldMessage);
21+
22+
expect(newMessage).toEqual(oldMessage);
23+
});
24+
});

src/utils/__tests__/color.ts

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import { changeColorToClassName, Colors } from '../color';
2+
import { truncateString } from '../index';
3+
4+
describe('color', () => {
5+
it('check all color enum exist', () => {
6+
expect(Colors.ONBACKGROUND_1).not.toBe(undefined);
7+
expect(Colors.ONBACKGROUND_2).not.toBe(undefined);
8+
expect(Colors.ONBACKGROUND_3).not.toBe(undefined);
9+
expect(Colors.ONBACKGROUND_4).not.toBe(undefined);
10+
expect(Colors.ONCONTENT_1).not.toBe(undefined);
11+
expect(Colors.PRIMARY).not.toBe(undefined);
12+
expect(Colors.ERROR).not.toBe(undefined);
13+
});
14+
15+
it('change color enum to proper className', () => {
16+
for (const color of Object.values(Colors)) {
17+
expect(changeColorToClassName(color)).toBe(`sendbird-color--${color.toLowerCase().replace('_', '-')}`);
18+
}
19+
20+
const nonColor = 'not-existing-color-enum-value';
21+
expect(changeColorToClassName(nonColor)).toBe('');
22+
});
23+
});
24+
25+
describe('truncateString', () => {
26+
it('truncate string properly by the given parameter', () => {
27+
expect(truncateString('this is full string', 10)).toBe('this...ing');
28+
});
29+
});
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import { render, waitFor, screen } from '@testing-library/react';
2+
import useDidMountEffect from '../useDidMountEffect';
3+
import React, { useState } from 'react';
4+
5+
describe('useDidMountEffect', () => {
6+
beforeEach(() => {
7+
jest.restoreAllMocks();
8+
});
9+
10+
it('ignore callback if didMount was false', () => {
11+
const mockCallback = jest.fn();
12+
13+
const TestComponent = () => {
14+
const [counter, setCounter] = useState(0);
15+
useDidMountEffect(mockCallback, [counter]);
16+
return (<button onClick={() => setCounter(counter + 1)}>increment</button>);
17+
};
18+
19+
render(<TestComponent />);
20+
21+
expect(mockCallback).not.toHaveBeenCalled();
22+
});
23+
24+
it('call callback if didMount was true', async () => {
25+
const mockCallback = jest.fn();
26+
27+
const TestComponent = () => {
28+
const [counter, setCounter] = useState(0);
29+
useDidMountEffect(mockCallback, [counter]);
30+
return (<button onClick={() => setCounter(counter + 1)}>increment</button>);
31+
};
32+
33+
render(<TestComponent />);
34+
const button = screen.getByText('increment');
35+
36+
await waitFor(() => {
37+
button.click();
38+
});
39+
40+
await waitFor(() => {
41+
button.click();
42+
});
43+
44+
await waitFor(() => {
45+
expect(mockCallback).toHaveBeenCalledTimes(2);
46+
});
47+
});
48+
});

src/utils/__tests__/utils.spec.ts

Lines changed: 36 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import {
33
isFileMessage,
44
isUrl,
55
isUserMessage,
6-
isMultipleFilesMessage, isDefaultChannelName, DEFAULT_GROUP_CHANNEL_NAME, DEFAULT_AI_CHATBOT_CHANNEL_NAME,
6+
isMultipleFilesMessage, isDefaultChannelName, DEFAULT_GROUP_CHANNEL_NAME, DEFAULT_AI_CHATBOT_CHANNEL_NAME, arrayEqual,
77
} from '../index';
88
import { AdminMessage, FileMessage, MultipleFilesMessage, UserMessage } from '@sendbird/chat/message';
99
import { delay, deleteNullish } from '../utils';
@@ -237,6 +237,8 @@ describe('deleteNullish', () => {
237237
});
238238

239239
describe('delay', () => {
240+
const errorBound = 5;
241+
240242
it('should resolve after the specified time', async () => {
241243
const start = Date.now();
242244
const delayTime = 100;
@@ -247,7 +249,7 @@ describe('delay', () => {
247249
const elapsed = end - start;
248250

249251
// Check if the elapsed time is at least the delay time
250-
expect(elapsed).toBeGreaterThanOrEqual(delayTime);
252+
expect(elapsed).toBeGreaterThanOrEqual(delayTime - errorBound);
251253
});
252254

253255
it('should resolve immediately for 0 milliseconds', async () => {
@@ -259,7 +261,7 @@ describe('delay', () => {
259261
const elapsed = end - start;
260262

261263
// Check if the elapsed time is very small
262-
expect(elapsed).toBeLessThan(10);
264+
expect(elapsed).toBeLessThan(errorBound);
263265
});
264266
it('should resolve immediately when no parameter is provided', async () => {
265267
const start = Date.now();
@@ -269,7 +271,7 @@ describe('delay', () => {
269271
const end = Date.now();
270272
const elapsed = end - start;
271273

272-
expect(elapsed).toBeLessThan(10);
274+
expect(elapsed).toBeLessThan(errorBound);
273275
});
274276
});
275277

@@ -320,3 +322,33 @@ describe('isDefaultChannelName', () => {
320322
expect(result).toBe(false);
321323
});
322324
});
325+
326+
describe('arrayEqual', () => {
327+
it('return true if two arrays are equal', () => {
328+
const arr1 = ['elem', 2, true];
329+
const arr2 = ['elem', 2, true];
330+
331+
expect(arrayEqual(arr1, arr2)).toBe(true);
332+
});
333+
334+
it('return false if two arrays are not equal', () => {
335+
const arr1 = ['elem', 2, true];
336+
const arr2 = ['elem', 42, false];
337+
338+
expect(arrayEqual(arr1, arr2)).toBe(false);
339+
});
340+
341+
it('return false if two array doesn\'t have same length', () => {
342+
const arr1 = ['elem', 2, true];
343+
const arr2 = ['elem', 42];
344+
345+
expect(arrayEqual(arr1, arr2)).toBe(false);
346+
});
347+
348+
it('return false if the one of parameter is not array', () => {
349+
const arr1 = ['elem', 2, true];
350+
const arr2 = {};
351+
352+
expect(arrayEqual(arr1, arr2)).toBe(false);
353+
});
354+
});

src/utils/color.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ export enum Colors {
66
ONBACKGROUND_3 = 'ONBACKGROUND_3',
77
ONBACKGROUND_4 = 'ONBACKGROUND_4',
88
ONCONTENT_1 = 'ONCONTENT_1',
9-
ONCONTENT_2 = 'ONCONTENT_2',
109
PRIMARY = 'PRIMARY',
1110
ERROR = 'ERROR',
1211
}

src/utils/index.ts

Lines changed: 2 additions & 68 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import SendbirdChat, { Emoji, EmojiCategory, EmojiContainer, User } from '@sendbird/chat';
2-
import { GroupChannel, Member, SendbirdGroupChat, GroupChannelListQuery, GroupChannelListOrder } from '@sendbird/chat/groupChannel';
1+
import { Emoji, EmojiCategory, EmojiContainer, User } from '@sendbird/chat';
2+
import { GroupChannel, Member, GroupChannelListQuery, GroupChannelListOrder } from '@sendbird/chat/groupChannel';
33
import {
44
AdminMessage,
55
BaseMessage,
@@ -10,7 +10,6 @@ import {
1010
UploadedFileInfo,
1111
UserMessage,
1212
} from '@sendbird/chat/message';
13-
import { OpenChannel, SendbirdOpenChat } from '@sendbird/chat/openChannel';
1413
import { SendableMessage } from '@sendbird/chat/lib/__definition';
1514

1615
import { getOutgoingMessageState, OutgoingMessageStates } from './exports/getOutgoingMessageState';
@@ -217,13 +216,6 @@ const SendingMessageStatus: SendingMessageStatus = {
217216
export type CoreMessageType = AdminMessage | UserMessage | FileMessage | MultipleFilesMessage;
218217
export type SendableMessageType = UserMessage | FileMessage | MultipleFilesMessage;
219218

220-
export const isTextuallyNull = (text: string): boolean => {
221-
if (text === '' || text === null) {
222-
return true;
223-
}
224-
return false;
225-
};
226-
227219
export const isMOVType = (type: string): boolean => type === 'video/quicktime';
228220
/**
229221
* @link: https://sendbird.atlassian.net/browse/SBISSUE-16031?focusedCommentId=270601
@@ -452,15 +444,6 @@ export const getClassName = (classNames: string | Array<string | Array<string>>)
452444
: classNames
453445
);
454446

455-
export const startsWithAtAndEndsWithBraces = (str: string) => {
456-
const regex = /^\{@.*\}$/;
457-
return regex.test(str);
458-
};
459-
460-
export const removeAtAndBraces = (str: string) => {
461-
return str.replace(/^\{@|}$/g, '');
462-
};
463-
464447
export const isReactedBy = (userId: string, reaction: Reaction): boolean => (
465448
reaction.userIds.some((reactorUserId: string): boolean => reactorUserId === userId)
466449
);
@@ -480,33 +463,6 @@ export const getEmojiTooltipString = (reaction: Reaction, userId: string, member
480463
.join(', ')}${you}`);
481464
};
482465

483-
// TODO: Use the interface after language tranlsatation of Sendbird.js
484-
interface UIKitStore {
485-
stores: {
486-
sdkStore: {
487-
sdk: SendbirdChat | SendbirdOpenChat | SendbirdGroupChat,
488-
},
489-
userStore: {
490-
user: User,
491-
},
492-
},
493-
config: {
494-
isReactionEnabled: boolean,
495-
htmlTextDirection: HTMLTextDirection,
496-
forceLeftToRightMessageLayout: boolean,
497-
}
498-
}
499-
export const getCurrentUserId = (store: UIKitStore): string => (store?.stores?.userStore?.user?.userId);
500-
export const getUseReaction = (store: UIKitStore, channel: GroupChannel | OpenChannel): boolean => {
501-
if (!store?.config?.isReactionEnabled)
502-
return false;
503-
if (!store?.stores?.sdkStore?.sdk?.appInfo?.useReaction)
504-
return false;
505-
if (channel?.isGroupChannel())
506-
return !((channel as GroupChannel).isBroadcast || (channel as GroupChannel).isSuper);
507-
return store?.config?.isReactionEnabled;
508-
};
509-
510466
export function getSuggestedReplies(message?: BaseMessage): string[] {
511467
if (message?.extendedMessagePayload && Array.isArray(message?.extendedMessagePayload?.suggested_replies)) {
512468
return message.extendedMessagePayload.suggested_replies;
@@ -515,22 +471,12 @@ export function getSuggestedReplies(message?: BaseMessage): string[] {
515471
}
516472
}
517473

518-
export const isMessageSentByMe = (
519-
userId: string,
520-
message: SendableMessageType,
521-
): boolean => (
522-
!!(userId && message?.sender?.userId && userId === message.sender.userId)
523-
);
524-
525474
const URL_REG = /^((http|https):\/\/)?([a-z\d-]+\.)+[a-z]{2,}(\:[0-9]{1,5})?(\/[-a-zA-Z\d%_.~+&=]*)*(\?[;&a-zA-Z\d%_.~+=-]*)?(#\S*)?$/;
526475
/** @deprecated
527476
* URL detection in a message text will be handled in utils/tokens/tokenize.ts
528477
*/
529478
export const isUrl = (text: string): boolean => URL_REG.test(text);
530479

531-
const MENTION_TAG_REG = /\@\{.*?\}/i;
532-
export const isMentionedText = (text: string): boolean => MENTION_TAG_REG.test(text);
533-
534480
export const truncateString = (fullStr: string, strLen?: number): string => {
535481
if (!strLen) strLen = 40;
536482
if (fullStr === null || fullStr === undefined) return '';
@@ -897,18 +843,6 @@ export const getChannelsWithUpsertedChannel = (
897843
return sortChannelList(channels, order ?? GroupChannelListOrder.LATEST_LAST_MESSAGE);
898844
};
899845

900-
export const getMatchedUserIds = (word: string, users: Array<User>, _template?: string): boolean => {
901-
const template = _template || '@'; // Use global variable
902-
// const matchedUserIds = [];
903-
// users.map((user) => user?.userId).forEach((userId) => {
904-
// if (word.indexOf(`${template}{${userId}}`) > -1) {
905-
// matchedUserIds.push(userId);
906-
// }
907-
// });
908-
// return matchedUserIds;
909-
return users.map((user) => user?.userId).some((userId) => word.indexOf(`${template}{${userId}}`) > -1);
910-
};
911-
912846
export enum StringObjType {
913847
normal = 'normal',
914848
mention = 'mention',

src/utils/useDidMountEffect.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
11
import { useEffect, useState } from 'react';
22

33
const useDidMountEffect = (func: () => void, deps: Array<unknown>): void => {
4-
const [didMount, setDidmount] = useState(false);
4+
const [didMount, setDidMount] = useState(false);
55
useEffect(() => {
66
if (didMount) {
77
func();
88
} else {
9-
setDidmount(true);
9+
setDidMount(true);
1010
}
1111
}, deps);
1212
};

0 commit comments

Comments
 (0)