snapshot of https://github.com/RocketChat/Rocket.Chat.git (develop, 2026-09-16; blobs > 131072B omitted)
Some checks failed
Create issues from TODOs / todos (push) Failing after 3s
Close inactive issues / close-issues (push) Has been cancelled
Deploy GitHub Pages / deploy-preview (push) Has been cancelled
CI / ⚙️ Variables Setup (push) Has been cancelled
CI / ⚙️ Test Guard (push) Has been cancelled
CI / 🚀 Notify external services - draft (push) Has been cancelled
CI / 📦 Build Packages (push) Has been cancelled
CI / 📦 Meteor Build (coverage) (push) Has been cancelled
CI / 📦 Meteor Build (production) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [account-service presence-service omnichannel-transcript-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [authorization-service queue-worker-service ddp-streamer-service], fips) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Build Docker (amd64, [rocketchat], fips) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [account-service presence-service omnichannel-transcript-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [authorization-service queue-worker-service ddp-streamer-service], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], ${{ (github.event_name != 'release' && github.ref != 'refs/heads/develop') && 'coverage' || 'production' }}) (push) Has been cancelled
CI / 🚢 Build Docker (arm64, [rocketchat], coverage) (push) Has been cancelled
CI / 🚢 Publish Docker Images (ghcr.io) (push) Has been cancelled
CI / 📦 Track Image Sizes (push) Has been cancelled
CI / 🔎 Code Check - Action Lint (push) Has been cancelled
CI / 🔎 Code Check (push) Has been cancelled
CI / 🔨 Test Storybook (push) Has been cancelled
CI / 🔨 Test Unit (push) Has been cancelled
CI / 🔨 Test API (CE) (push) Has been cancelled
CI / 🔨 Test API Livechat (CE) (push) Has been cancelled
CI / 🔨 Test UI (CE) (push) Has been cancelled
CI / 🔨 Test API (EE) (push) Has been cancelled
CI / 🔨 Test API Livechat (EE) (push) Has been cancelled
CI / 🔨 Test API Apps (deno-runtime - EE) (push) Has been cancelled
CI / 🔨 Test UI (EE) (push) Has been cancelled
CI / 🔨 Test API (FIPS) (push) Has been cancelled
CI / 🔨 Test API Livechat (FIPS) (push) Has been cancelled
CI / 🔨 Test UI (FIPS) (push) Has been cancelled
CI / 🔨 Test Federation Matrix (push) Has been cancelled
CI / 📊 Report Coverage (push) Has been cancelled
CI / ✅ Tests Done (push) Has been cancelled
CI / 🚀 Publish build assets (push) Has been cancelled
CI / 🚀 Publish Docker Images (DockerHub) (push) Has been cancelled
CI / 🚀 Notify external services (push) Has been cancelled
CI / Update Version Durability (push) Has been cancelled
Release / Release (push) Has been cancelled
Auto-close duplicate issues / auto-close-duplicates (push) Failing after 1s
Code scanning - action / CodeQL-Build (push) Failing after 1s

This commit is contained in:
upstream-mirror
2026-09-16 01:21:02 +05:00
commit 30810eecd7
10161 changed files with 987110 additions and 0 deletions

View File

@@ -0,0 +1,18 @@
import { expect } from 'chai';
const messages = {
'Sample Message': 14,
'Sample 1 ⛳': 10,
'Sample 2 ❤': 10,
'Sample 3 ⛳❤⛳❤': 13,
};
describe('Message Properties', () => {
describe('Check Message Length', () => {
Object.keys(messages).forEach((objectKey) => {
it('should treat emojis as single characters', () => {
expect(objectKey.length).to.be.equal(messages[objectKey]);
});
});
});
});

View File

@@ -0,0 +1,90 @@
import type { MessageTypesValues, IRoom, IUser } from '@rocket.chat/core-typings';
import { expect } from 'chai';
import { getHiddenSystemMessages } from '../../../../../server/lib/messaging/getHiddenSystemMessages';
describe('getHiddenSystemMessages', () => {
it('should return room.sysMes if it is an array', async () => {
const room: IRoom = {
_id: 'roomId',
sysMes: ['mute_unmute', 'room_changed_description'] as MessageTypesValues[],
t: 'c',
msgs: 0,
u: {} as IUser,
usersCount: 0,
_updatedAt: new Date(),
};
const result = getHiddenSystemMessages(room, []);
expect(result).to.deep.equal(room.sysMes);
});
it('should return cached hidden system messages if room.sysMes is not an array', async () => {
const cachedHiddenSystemMessage: MessageTypesValues[] = ['mute_unmute', 'room_changed_description'];
const room: IRoom = {
_id: 'roomId',
t: 'c',
msgs: 0,
u: {} as IUser,
usersCount: 0,
_updatedAt: new Date(),
};
const result = getHiddenSystemMessages(room, cachedHiddenSystemMessage);
expect(result).to.deep.equal(['user-muted', 'user-unmuted', 'room_changed_description']);
});
it('should return an empty array if both room.sysMes and cached hidden system messages are undefined', async () => {
const room: IRoom = {
_id: 'roomId',
t: 'c',
msgs: 0,
u: {} as IUser,
usersCount: 0,
_updatedAt: new Date(),
};
const result = getHiddenSystemMessages(room, []);
expect(result).to.deep.equal([]);
});
it('should return cached hidden system messages if room.sysMes is null', async () => {
const cachedHiddenSystemMessage: MessageTypesValues[] = ['subscription-role-added', 'room_changed_announcement'];
const room: IRoom = {
_id: 'roomId',
sysMes: undefined,
t: 'c',
msgs: 0,
u: {} as IUser,
usersCount: 0,
_updatedAt: new Date(),
};
const result = getHiddenSystemMessages(room, cachedHiddenSystemMessage);
expect(result).to.deep.equal(cachedHiddenSystemMessage);
});
it('should return cached hidden system messages if room.sysMes array and hidden system message is available', async () => {
const cachedHiddenSystemMessage: MessageTypesValues[] = ['room_changed_announcement', 'room-archived'];
const room: IRoom = {
_id: 'roomId',
sysMes: ['mute_unmute', 'room_changed_description'] as MessageTypesValues[],
t: 'c',
msgs: 0,
u: {} as IUser,
usersCount: 0,
_updatedAt: new Date(),
};
const result = getHiddenSystemMessages(room, cachedHiddenSystemMessage);
expect(result).to.deep.equal(['mute_unmute', 'room_changed_description']);
});
});

View File

@@ -0,0 +1,287 @@
import { expect } from 'chai';
import { MentionsServer } from '../../../../../../server/lib/messaging/mentions/Mentions';
let mention;
beforeEach(() => {
mention = new MentionsServer({
pattern: () => '[0-9a-zA-Z-_.]+',
messageMaxAll: () => 4, // || RocketChat.settings.get('Message_MaxAll')
getUsers: async (usernames) =>
[
{
_id: 1,
username: 'rocket.cat',
},
{
_id: 2,
username: 'jon',
},
].filter((user) => usernames.includes(user.username)), // Meteor.users.find({ username: {$in: _.unique(usernames)}}, { fields: {_id: true, username: true }}).fetch();
getChannels(channels) {
return [
{
_id: 1,
name: 'general',
},
].filter((channel) => channels.includes(channel.name));
// return RocketChat.models.Rooms.find({ name: {$in: _.unique(channels)}, t: 'c' }, { fields: {_id: 1, name: 1 }}).fetch();
},
getUser: (userId) => ({ _id: userId, language: 'en' }),
getTotalChannelMembers: (/* rid*/) => 2,
});
});
describe('Mention Server', () => {
describe('getUsersByMentions', () => {
describe('for @all but the number of users is greater than messageMaxAll', () => {
beforeEach(() => {
mention.getTotalChannelMembers = () => 5;
});
it('should return nothing', async () => {
const message = {
msg: '@all',
};
const expected = [];
const result = await mention.getUsersByMentions(message);
expect(expected).to.be.deep.equal(result);
});
});
describe('for one user', () => {
beforeEach(() => {
mention.getChannel = () => ({
usernames: [
{
_id: 1,
username: 'rocket.cat',
},
{
_id: 2,
username: 'jon',
},
],
});
// Meteor.users.find({ username: {$in: _.unique(usernames)}}, { fields: {_id: true, username: true }}).fetch();
});
it('should return "all"', async () => {
const message = {
msg: '@all',
};
const expected = [
{
_id: 'all',
username: 'all',
},
];
const result = await mention.getUsersByMentions(message);
expect(expected).to.be.deep.equal(result);
});
it('should return "here"', async () => {
const message = {
msg: '@here',
};
const expected = [
{
_id: 'here',
username: 'here',
},
];
const result = await mention.getUsersByMentions(message);
expect(expected).to.be.deep.equal(result);
});
it('should return "rocket.cat"', async () => {
const message = {
msg: '@rocket.cat',
};
const expected = [
{
_id: 1,
username: 'rocket.cat',
},
];
const result = await mention.getUsersByMentions(message);
expect(expected).to.be.deep.equal(result);
});
});
describe('for two user', () => {
it('should return "all and here"', async () => {
const message = {
msg: '@all @here',
};
const expected = [
{
_id: 'all',
username: 'all',
},
{
_id: 'here',
username: 'here',
},
];
const result = await mention.getUsersByMentions(message);
expect(expected).to.be.deep.equal(result);
});
it('should return "here and rocket.cat"', async () => {
const message = {
msg: '@here @rocket.cat',
};
const expected = [
{
_id: 'here',
username: 'here',
},
{
_id: 1,
username: 'rocket.cat',
},
];
const result = await mention.getUsersByMentions(message);
expect(expected).to.be.deep.equal(result);
});
it('should return "here, rocket.cat, jon"', async () => {
const message = {
msg: '@here @rocket.cat @jon',
};
const expected = [
{
_id: 'here',
username: 'here',
},
{
_id: 1,
username: 'rocket.cat',
},
{
_id: 2,
username: 'jon',
},
];
const result = await mention.getUsersByMentions(message);
expect(expected).to.be.deep.equal(result);
});
});
describe('for an unknow user', () => {
it('should return "nothing"', async () => {
const message = {
msg: '@unknow',
};
const expected = [];
const result = await mention.getUsersByMentions(message);
expect(expected).to.be.deep.equal(result);
});
});
});
describe('getChannelbyMentions', () => {
it('should return the channel "general"', async () => {
const message = {
msg: '#general',
};
const expected = [
{
_id: 1,
name: 'general',
},
];
const result = await mention.getChannelbyMentions(message);
expect(result).to.be.deep.equal(expected);
});
it('should return nothing"', async () => {
const message = {
msg: '#unknow',
};
const expected = [];
const result = await mention.getChannelbyMentions(message);
expect(result).to.be.deep.equal(expected);
});
});
describe('execute', () => {
it('should return the channel "general"', async () => {
const message = {
msg: '#general',
};
const expected = [
{
_id: 1,
name: 'general',
},
];
const result = await mention.getChannelbyMentions(message);
expect(result).to.be.deep.equal(expected);
});
it('should return nothing"', async () => {
const message = {
msg: '#unknow',
};
const expected = {
msg: '#unknow',
mentions: [],
channels: [],
};
const result = await mention.execute(message);
expect(result).to.be.deep.equal(expected);
});
});
describe('getUserMentions', () => {
describe('for message with only an md link', () => {
const result = [];
[
'[@rocket.cat](https://rocket.chat)',
'[@rocket.cat](https://rocket.chat) hello',
'[@rocket.cat](https://rocket.chat) hello how are you?',
'[test](https://rocket.chat)',
].forEach((text) => {
it(`should return "${JSON.stringify(result)}" from "${text}"`, () => {
expect(result).to.be.deep.equal(mention.getUserMentions(text));
});
});
});
describe('for message with md link and text', () => {
const result = ['@sauron'];
[
'@sauron please work on [user@password](https://rocket.chat)',
'@sauron hello [user@password](https://rocket.chat) hello',
'[user@password](https://rocket.chat) hello @sauron',
'@sauron please work on [user@password](https://rocket.chat) hello',
].forEach((text) => {
it(`should return "${JSON.stringify(result)}" from "${text}"`, () => {
expect(result).to.be.deep.equal(mention.getUserMentions(text));
});
});
});
});
describe('getChannelMentions', () => {
describe('for message with md link', () => {
const result = [];
[
'[#general](https://rocket.chat)',
'[#general](https://rocket.chat) hello',
'[#general](https://rocket.chat) hello how are you?',
'[test #general #other](https://rocket.chat)',
].forEach((text) => {
it(`should return "${JSON.stringify(result)}" from "${text}"`, () => {
expect(result).to.be.deep.equal(mention.getChannelMentions(text));
});
});
});
describe('for message with md link and text', () => {
const result = ['#somechannel'];
[
'#somechannel please [user#password](https://rocket.chat)',
'#somechannel hello [user#password](https://rocket.chat) hello',
'[user#password](https://rocket.chat) hello #somechannel',
'#somechannel join [#general on #other](https://rocket.chat)',
].forEach((text) => {
it(`should return "${JSON.stringify(result)}" from "${text}"`, () => {
expect(result).to.be.deep.equal(mention.getChannelMentions(text));
});
});
});
});
});

View File

@@ -0,0 +1,430 @@
import { expect } from 'chai';
import { beforeEach, describe, it } from 'mocha';
import p from 'proxyquire';
import sinon from 'sinon';
const meteorMethodsMock = sinon.stub();
const emojiList: Record<string, any> = {};
const modelsMock = {
EmojiCustom: {
countByNameOrAlias: sinon.stub(),
},
Users: {
findOneById: sinon.stub(),
},
Messages: {
findOneById: sinon.stub(),
setReactions: sinon.stub(),
unsetReactions: sinon.stub(),
},
Rooms: {
findOneById: sinon.stub(),
unsetReactionsInLastMessage: sinon.stub(),
setReactionsInLastMessage: sinon.stub(),
},
};
const canAccessRoomAsyncMock = sinon.stub();
const isTheLastMessageMock = sinon.stub();
const notifyOnMessageChangeMock = sinon.stub();
const hasPermissionAsyncMock = sinon.stub();
const i18nMock = { t: sinon.stub() };
const callbacksRunMock = sinon.stub();
const meteorErrorMock = class extends Error {
constructor(message: string) {
super(message);
}
};
const { removeUserReaction, executeSetReaction, setReaction } = p
.noCallThru()
.load('../../../../../../server/lib/messaging/reactions/setReaction.ts', {
'@rocket.chat/models': modelsMock,
'@rocket.chat/core-services': { Message: { beforeReacted: sinon.stub() } },
'meteor/meteor': { Meteor: { methods: meteorMethodsMock, Error: meteorErrorMock } },
'../../callbacks': { callbacks: { run: callbacksRunMock } },
'../../i18n': { i18n: i18nMock },
'../../authorization': { canAccessRoomAsync: canAccessRoomAsyncMock },
'../../authorization/hasPermission': { hasPermissionAsync: hasPermissionAsyncMock },
'../emoji': { emoji: { list: emojiList } },
'../../messages/isTheLastMessage': { isTheLastMessage: isTheLastMessageMock },
'../../notifyListener': {
notifyOnMessageChange: notifyOnMessageChangeMock,
},
});
describe('Reactions', () => {
describe('removeUserReaction', () => {
it('should return the message unmodified when no reactions exist', () => {
const message = {};
const result = removeUserReaction(message as any, 'test', 'test');
expect(result).to.equal(message);
});
it('should remove the reaction from a message', () => {
const message = {
reactions: {
test: {
usernames: ['test', 'test2'],
},
},
};
const result = removeUserReaction(message as any, 'test', 'test');
expect(result.reactions.test.usernames).to.not.include('test');
expect(result.reactions.test.usernames).to.include('test2');
});
it('should remove the reaction from a message when the user is the last one on the array', () => {
const message = {
reactions: {
test: {
usernames: ['test'],
},
},
};
const result = removeUserReaction(message as any, 'test', 'test');
expect(result.reactions.test).to.be.undefined;
});
it('should remove username only from the reaction thats passed in', () => {
const message = {
reactions: {
test: {
usernames: ['test', 'test2'],
},
other: {
usernames: ['test', 'test2'],
},
},
};
const result = removeUserReaction(message as any, 'test', 'test');
expect(result.reactions.test.usernames).to.not.include('test');
expect(result.reactions.test.usernames).to.include('test2');
expect(result.reactions.other.usernames).to.include('test');
expect(result.reactions.other.usernames).to.include('test2');
});
it('should do nothing if username is not in the reaction', () => {
const message = {
reactions: {
test: {
usernames: ['test', 'test2'],
},
},
};
const result = removeUserReaction(message as any, 'test', 'test3');
expect(result.reactions.test.usernames).to.not.include('test3');
expect(result.reactions.test.usernames).to.include('test');
expect(result.reactions.test.usernames).to.include('test2');
});
});
describe('executeSetReaction', () => {
beforeEach(() => {
modelsMock.EmojiCustom.countByNameOrAlias.reset();
});
it('should throw an error if reaction is not on emoji list', async () => {
modelsMock.EmojiCustom.countByNameOrAlias.resolves(0);
await expect(executeSetReaction('test', 'test', 'test')).to.be.rejectedWith('error-not-allowed');
});
it('should fail if user does not exist', async () => {
modelsMock.EmojiCustom.countByNameOrAlias.resolves(1);
await expect(executeSetReaction('test', 'test', 'test')).to.be.rejectedWith('error-invalid-user');
});
it('should fail if message does not exist', async () => {
modelsMock.EmojiCustom.countByNameOrAlias.resolves(1);
modelsMock.Users.findOneById.resolves({ username: 'test' });
await expect(executeSetReaction('test', 'test', 'test')).to.be.rejectedWith('error-not-allowed');
});
it('should return nothing if user already reacted and its trying to react again', async () => {
modelsMock.EmojiCustom.countByNameOrAlias.resolves(1);
modelsMock.Users.findOneById.resolves({ username: 'test' });
modelsMock.Messages.findOneById.resolves({ reactions: { ':test:': { usernames: ['test'] } } });
expect(await executeSetReaction('test', 'test', 'test', true)).to.be.undefined;
});
it('should return nothing if user hasnt reacted and its trying to unreact', async () => {
modelsMock.EmojiCustom.countByNameOrAlias.resolves(1);
modelsMock.Users.findOneById.resolves({ username: 'test' });
modelsMock.Messages.findOneById.resolves({ reactions: { ':test:': { usernames: ['testxxxx'] } } });
expect(await executeSetReaction('test', 'test', 'test', false)).to.be.undefined;
});
it('should fail if room does not exist', async () => {
modelsMock.EmojiCustom.countByNameOrAlias.resolves(1);
modelsMock.Users.findOneById.resolves({ username: 'test' });
modelsMock.Messages.findOneById.resolves({ reactions: { ':test:': { usernames: ['test'] } } });
modelsMock.Rooms.findOneById.resolves(undefined);
await expect(executeSetReaction('test', 'test', 'test')).to.be.rejectedWith('error-not-allowed');
});
it('should fail if user doesnt have acccess to the room', async () => {
modelsMock.EmojiCustom.countByNameOrAlias.resolves(1);
modelsMock.Users.findOneById.resolves({ username: 'test' });
modelsMock.Messages.findOneById.resolves({ reactions: { ':test:': { usernames: ['test'] } } });
modelsMock.Rooms.findOneById.resolves({ t: 'd' });
canAccessRoomAsyncMock.resolves(false);
await expect(executeSetReaction('test', 'test', 'test')).to.be.rejectedWith('not-authorized');
});
it('should call setReaction with correct params', async () => {
modelsMock.EmojiCustom.countByNameOrAlias.resolves(1);
modelsMock.Users.findOneById.resolves({ username: 'test' });
modelsMock.Messages.findOneById.resolves({ reactions: { ':test:': { usernames: ['test'] } } });
modelsMock.Rooms.findOneById.resolves({ t: 'c' });
canAccessRoomAsyncMock.resolves(true);
const res = await executeSetReaction('test', 'test', 'test');
expect(res).to.be.undefined;
});
it('should use the message from param when the type is not an string', async () => {
modelsMock.EmojiCustom.countByNameOrAlias.resolves(1);
modelsMock.Users.findOneById.resolves({ username: 'test' });
modelsMock.Rooms.findOneById.resolves({ t: 'c' });
canAccessRoomAsyncMock.resolves(true);
await executeSetReaction('test', 'test', { reactions: { ':test:': { usernames: ['test'] } } });
expect(modelsMock.Messages.findOneById.calledOnce).to.be.false;
});
});
describe('setReaction', () => {
beforeEach(() => {
canAccessRoomAsyncMock.reset();
hasPermissionAsyncMock.reset();
isTheLastMessageMock.reset();
modelsMock.Messages.setReactions.reset();
modelsMock.Rooms.setReactionsInLastMessage.reset();
modelsMock.Rooms.unsetReactionsInLastMessage.reset();
modelsMock.Messages.unsetReactions.reset();
callbacksRunMock.reset();
});
it('should throw an error if user is muted from the room', async () => {
const room = {
muted: ['test'],
};
const user = {
username: 'test',
};
const message = {
_id: 'test',
};
await expect(setReaction(room, user, message, ':test:')).to.be.rejectedWith('error-not-allowed');
});
it('should throw an error if room is readonly and cannot be reacted when readonly and user trying doesnt have permissions and user is not unmuted from room', async () => {
const room = {
ro: true,
reactWhenReadOnly: false,
};
const user = {
username: 'test',
};
const message = {
_id: 'test',
};
canAccessRoomAsyncMock.resolves(false);
await expect(setReaction(room, user, message, ':test:')).to.be.rejectedWith("You can't send messages because the room is readonly.");
});
it('should remove the user reaction if userAlreadyReacted is true and call unsetReaction if reaction is the last one on message', async () => {
const room = {
_id: 'test',
};
const user = {
username: 'test',
};
const message = {
_id: 'test',
reactions: {
':test:': {
usernames: ['test'],
},
},
};
const reaction = ':test:';
await setReaction(room, user, message, reaction, true);
expect(modelsMock.Messages.unsetReactions.calledWith(message._id)).to.be.true;
});
it('should call Rooms.unsetReactionsInLastMessage when userAlreadyReacted is true and reaction is the last one on message', async () => {
const room = {
_id: 'test',
lastMessage: 'test',
};
const user = {
username: 'test',
};
const message = {
_id: 'test',
reactions: {
':test:': {
usernames: ['test'],
},
},
};
const reaction = ':test:';
isTheLastMessageMock.resolves(true);
await setReaction(room, user, message, reaction, true);
expect(modelsMock.Messages.unsetReactions.calledWith(message._id)).to.be.true;
expect(modelsMock.Rooms.unsetReactionsInLastMessage.calledWith(room._id)).to.be.true;
});
it('should update the reactions object when userAlreadyReacted is true and there is more reactions on message', async () => {
const room = {
_id: 'test',
};
const user = {
username: 'test',
};
const message = {
_id: 'test',
reactions: {
':test:': {
usernames: ['test'],
},
':test2:': {
usernames: ['test'],
},
},
};
const reaction = ':test:';
await setReaction(room, user, message, reaction, true);
expect(modelsMock.Messages.setReactions.calledWith(message._id, sinon.match({ ':test2:': { usernames: ['test'] } }))).to.be.true;
});
it('should call Rooms.setReactionsInLastMessage when userAlreadyReacted is true and reaction is not the last one on message', async () => {
const room = {
_id: 'test',
lastMessage: 'test',
};
const user = {
username: 'test',
};
const message = {
_id: 'test',
reactions: {
':test:': {
usernames: ['test'],
},
':test2:': {
usernames: ['test'],
},
},
};
const reaction = ':test:';
isTheLastMessageMock.resolves(true);
await setReaction(room, user, message, reaction, true);
expect(modelsMock.Messages.setReactions.calledWith(message._id, sinon.match({ ':test2:': { usernames: ['test'] } }))).to.be.true;
expect(modelsMock.Rooms.setReactionsInLastMessage.calledWith(room._id, sinon.match({ ':test2:': { usernames: ['test'] } }))).to.be
.true;
});
it('should call afterUnsetReaction callback when userAlreadyReacted is true', async () => {
const room = {
_id: 'test',
};
const user = {
username: 'test',
};
const message = {
_id: 'test',
reactions: {
':test:': {
usernames: ['test'],
},
},
};
const reaction = ':test:';
await setReaction(room, user, message, reaction, true);
expect(
callbacksRunMock.calledWith(
'afterUnsetReaction',
sinon.match({ _id: 'test' }),
sinon.match({ user, reaction, shouldReact: false, oldMessage: message }),
),
).to.be.true;
});
it('should set reactions when userAlreadyReacted is false', async () => {
const room = {
_id: 'test',
};
const user = {
username: 'test',
};
const message = {
_id: 'test',
};
const reaction = ':test:';
await setReaction(room, user, message, reaction, false);
expect(modelsMock.Messages.setReactions.calledWith(message._id, sinon.match({ ':test:': { usernames: ['test'] } }))).to.be.true;
});
it('should properly add username to the list of reactions when userAlreadyReacted is false', async () => {
const room = {
_id: 'test',
};
const user = {
username: 'test2',
};
const message = {
_id: 'test',
reactions: {
':test:': {
usernames: ['test'],
},
},
};
const reaction = ':test:';
await setReaction(room, user, message, reaction, false);
expect(modelsMock.Messages.setReactions.calledWith(message._id, sinon.match({ ':test:': { usernames: ['test', 'test2'] } }))).to.be
.true;
});
it('should call Rooms.setReactionInLastMessage when userAlreadyReacted is false', async () => {
const room = {
_id: 'x5',
lastMessage: 'test',
};
const user = {
username: 'test',
};
const message = {
_id: 'test',
};
const reaction = ':test:';
isTheLastMessageMock.resolves(true);
await setReaction(room, user, message, reaction, false);
expect(modelsMock.Messages.setReactions.calledWith(message._id, sinon.match({ ':test:': { usernames: ['test'] } }))).to.be.true;
expect(modelsMock.Rooms.setReactionsInLastMessage.calledWith(room._id, sinon.match({ ':test:': { usernames: ['test'] } }))).to.be
.true;
});
it('should call afterSetReaction callback when userAlreadyReacted is false', async () => {
const room = {
_id: 'test',
};
const user = {
username: 'test',
};
const message = {
_id: 'test',
};
const reaction = ':test:';
await setReaction(room, user, message, reaction, false);
expect(
callbacksRunMock.calledWith('afterSetReaction', sinon.match({ _id: 'test' }), sinon.match({ user, reaction, shouldReact: true })),
).to.be.true;
});
it('should return undefined on a successful reaction', async () => {
const room = {
_id: 'test',
};
const user = {
username: 'test',
};
const message = {
_id: 'test',
};
const reaction = ':test:';
expect(await setReaction(room, user, message, reaction, false)).to.be.undefined;
});
});
});

View File

@@ -0,0 +1,86 @@
import { expect } from 'chai';
import { validateCustomMessageFields } from '../../../../../server/lib/messaging/validateCustomMessageFields';
describe('validateCustomMessageFields', () => {
describe('When not enabled', () => {
it('should not allow to pass custom fields', () => {
const customFields = {
test: 'test',
};
expect(() => validateCustomMessageFields({ customFields, messageCustomFieldsEnabled: false, messageCustomFields: '' })).to.throw(
'Custom fields not enabled',
);
});
});
describe('When enabled', () => {
it('should not allow to pass invalid custom fields config', () => {
const customFields = {
test: 'test',
};
expect(() => validateCustomMessageFields({ customFields, messageCustomFieldsEnabled: true, messageCustomFields: '' })).to.throw(
'Unexpected end of JSON input',
);
});
it('should not allow to pass a property not present in config', () => {
const customFields = {
test: 'test',
};
const messageCustomFields = JSON.stringify({
properties: {
priority: {
type: 'string',
},
},
additionalProperties: true,
});
expect(() => validateCustomMessageFields({ customFields, messageCustomFieldsEnabled: true, messageCustomFields })).to.throw(
'Invalid custom fields',
);
});
it('should not allow to pass an invalid custom field value', () => {
const customFields = {
test: 123,
};
const messageCustomFields = JSON.stringify({
properties: {
priority: {
type: 'string',
},
},
additionalProperties: true,
});
expect(() => validateCustomMessageFields({ customFields, messageCustomFieldsEnabled: true, messageCustomFields })).to.throw(
'Invalid custom fields',
);
});
it('should not allow to pass anything different from an object', () => {
const customFields = [1, 2];
const messageCustomFields = JSON.stringify({
type: 'array',
items: [{ type: 'integer' }, { type: 'integer' }],
});
expect(() => validateCustomMessageFields({ customFields, messageCustomFieldsEnabled: true, messageCustomFields })).to.throw(
'Invalid custom fields config',
);
});
it('should allow to pass a valid custom fields config', () => {
const customFields = {
test: 'test',
};
const messageCustomFields = JSON.stringify({
properties: {
test: {
type: 'string',
},
},
});
expect(() => validateCustomMessageFields({ customFields, messageCustomFieldsEnabled: true, messageCustomFields })).to.not.throw();
});
});
});