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
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:
28
apps/meteor/tests/mocks/client/FakeChatProvider.tsx
Normal file
28
apps/meteor/tests/mocks/client/FakeChatProvider.tsx
Normal file
@@ -0,0 +1,28 @@
|
||||
import type { ReactNode } from 'react';
|
||||
|
||||
import { ChatContext } from '../../../client/views/room/contexts/ChatContext';
|
||||
import { createFakeSubscription } from '../data';
|
||||
|
||||
export type FakeChatProviderProps = {
|
||||
children?: ReactNode;
|
||||
};
|
||||
|
||||
const FakeChatProvider = ({ children }: FakeChatProviderProps) => {
|
||||
return (
|
||||
<ChatContext.Provider
|
||||
value={
|
||||
{
|
||||
data: {
|
||||
getSubscriptionFromMessage: async () => {
|
||||
return createFakeSubscription();
|
||||
},
|
||||
},
|
||||
} as any
|
||||
}
|
||||
>
|
||||
{children}
|
||||
</ChatContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export default FakeChatProvider;
|
||||
37
apps/meteor/tests/mocks/client/FakeRoomProvider.tsx
Normal file
37
apps/meteor/tests/mocks/client/FakeRoomProvider.tsx
Normal file
@@ -0,0 +1,37 @@
|
||||
import { faker } from '@faker-js/faker';
|
||||
import type { IRoom, ISubscription } from '@rocket.chat/core-typings';
|
||||
import type { ReactNode } from 'react';
|
||||
import { useMemo } from 'react';
|
||||
|
||||
import { RoomContext } from '../../../client/views/room/contexts/RoomContext';
|
||||
import { createFakeRoom, createFakeSubscription } from '../data';
|
||||
|
||||
export type FakeRoomProviderProps = {
|
||||
children?: ReactNode;
|
||||
roomOverrides?: Partial<IRoom>;
|
||||
subscriptionOverrides?: Partial<ISubscription>;
|
||||
};
|
||||
|
||||
const FakeRoomProvider = ({ children, roomOverrides, subscriptionOverrides }: FakeRoomProviderProps) => {
|
||||
return (
|
||||
<RoomContext.Provider
|
||||
value={useMemo(() => {
|
||||
const room = createFakeRoom(roomOverrides);
|
||||
const subscription = createFakeSubscription(subscriptionOverrides);
|
||||
|
||||
return {
|
||||
rid: room._id,
|
||||
room,
|
||||
hasMoreNextMessages: faker.datatype.boolean(),
|
||||
hasMorePreviousMessages: faker.datatype.boolean(),
|
||||
isLoadingMoreMessages: faker.datatype.boolean(),
|
||||
subscription,
|
||||
};
|
||||
}, [roomOverrides, subscriptionOverrides])}
|
||||
>
|
||||
{children}
|
||||
</RoomContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export default FakeRoomProvider;
|
||||
22
apps/meteor/tests/mocks/client/ModalContextMock.tsx
Normal file
22
apps/meteor/tests/mocks/client/ModalContextMock.tsx
Normal file
@@ -0,0 +1,22 @@
|
||||
import { ModalContext } from '@rocket.chat/ui-contexts';
|
||||
import type { ContextType, ReactNode } from 'react';
|
||||
import { useMemo } from 'react';
|
||||
|
||||
export type ModalContextMockProps = {
|
||||
children: ReactNode;
|
||||
};
|
||||
|
||||
const ModalContextMock = ({ children }: ModalContextMockProps) => {
|
||||
const value = useMemo(
|
||||
() => ({
|
||||
modal: {
|
||||
setModal: (): void => undefined,
|
||||
},
|
||||
}),
|
||||
[],
|
||||
);
|
||||
|
||||
return <ModalContext.Provider value={value as unknown as ContextType<typeof ModalContext>}>{children}</ModalContext.Provider>;
|
||||
};
|
||||
|
||||
export default ModalContextMock;
|
||||
119
apps/meteor/tests/mocks/client/RouterContextMock.tsx
Normal file
119
apps/meteor/tests/mocks/client/RouterContextMock.tsx
Normal file
@@ -0,0 +1,119 @@
|
||||
import type { To, SearchParameters, LocationPathname, LocationSearch } from '@rocket.chat/ui-contexts';
|
||||
import { RouterContext } from '@rocket.chat/ui-contexts';
|
||||
import { compile } from 'path-to-regexp';
|
||||
import { useRef, useMemo } from 'react';
|
||||
import type { MutableRefObject, ReactNode } from 'react';
|
||||
|
||||
const encodeSearchParameters = (searchParameters: SearchParameters) => {
|
||||
const search = new URLSearchParams();
|
||||
|
||||
for (const [key, value] of Object.entries(searchParameters)) {
|
||||
search.append(key, value);
|
||||
}
|
||||
|
||||
const searchString = search.toString();
|
||||
|
||||
return searchString ? (`?${searchString}` as `?${LocationSearch}`) : '';
|
||||
};
|
||||
|
||||
const buildRoutePath = (to: To): LocationPathname | `${LocationPathname}?${LocationSearch}` => {
|
||||
if (typeof to === 'string') {
|
||||
return to;
|
||||
}
|
||||
|
||||
if ('pathname' in to) {
|
||||
const { pathname, search = {} } = to;
|
||||
return (pathname + encodeSearchParameters(search)) as LocationPathname | `${LocationPathname}?${LocationSearch}`;
|
||||
}
|
||||
|
||||
if ('pattern' in to) {
|
||||
const { pattern, params = {}, search = {} } = to;
|
||||
return (compile(pattern, { encode: encodeURIComponent })(params) + encodeSearchParameters(search)) as
|
||||
LocationPathname | `${LocationPathname}?${LocationSearch}`;
|
||||
}
|
||||
|
||||
if ('name' in to) {
|
||||
const { name, params = {}, search = {} } = to;
|
||||
|
||||
switch (name) {
|
||||
case 'audit-home':
|
||||
return `/audit${encodeSearchParameters(search)}`;
|
||||
|
||||
case 'audit-log':
|
||||
return `/audit-log${encodeSearchParameters(search)}`;
|
||||
|
||||
case 'marketplace':
|
||||
return `/marketplace/${params.context}/${params.page}${encodeSearchParameters(search)}`;
|
||||
}
|
||||
|
||||
return (compile(name, { encode: encodeURIComponent })(params) + encodeSearchParameters(search)) as
|
||||
LocationPathname | `${LocationPathname}?${LocationSearch}`;
|
||||
}
|
||||
|
||||
throw new Error('Invalid route');
|
||||
};
|
||||
|
||||
export type RouterContextMockProps = {
|
||||
children?: ReactNode;
|
||||
navigate?: (toOrDelta: number | To) => void;
|
||||
currentPath?: MutableRefObject<string | undefined>;
|
||||
searchParameters?: Record<string, any>;
|
||||
routeParameters?: Record<string, any>;
|
||||
};
|
||||
|
||||
const RouterContextMock = ({ children, navigate, currentPath, searchParameters = {}, routeParameters = {} }: RouterContextMockProps) => {
|
||||
const history = useRef<{ stack: To[]; index: number }>({ stack: ['/'], index: 0 });
|
||||
|
||||
if (currentPath) {
|
||||
currentPath.current = buildRoutePath(history.current.stack[history.current.index]);
|
||||
}
|
||||
|
||||
return (
|
||||
<RouterContext.Provider
|
||||
value={useMemo(() => {
|
||||
return {
|
||||
subscribeToRouteChange: () => () => undefined,
|
||||
getLocationPathname: () => '/',
|
||||
getLocationSearch: () => '',
|
||||
getLocationHash: () => '',
|
||||
getRouteParameters: () => routeParameters,
|
||||
getSearchParameters: () => searchParameters,
|
||||
getRouteName: () => 'home',
|
||||
getPreviousRouteName: () => undefined,
|
||||
buildRoutePath,
|
||||
navigate:
|
||||
navigate ??
|
||||
((toOrDelta: number | To) => {
|
||||
if (typeof toOrDelta === 'number') {
|
||||
history.current.index += toOrDelta;
|
||||
|
||||
if (history.current.index < 0) {
|
||||
history.current.index = 0;
|
||||
}
|
||||
|
||||
if (history.current.index >= history.current.stack.length) {
|
||||
history.current.index = history.current.stack.length - 1;
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
history.current.stack = history.current.stack.slice(0, history.current.index + 1);
|
||||
history.current.stack.push(toOrDelta);
|
||||
history.current.index = history.current.stack.length - 1;
|
||||
|
||||
if (currentPath) {
|
||||
currentPath.current = buildRoutePath(history.current.stack[history.current.index]);
|
||||
}
|
||||
}),
|
||||
defineRoutes: () => () => undefined,
|
||||
getRoomRoute: () => ({ path: '/' }),
|
||||
};
|
||||
}, [currentPath, navigate, routeParameters, searchParameters])}
|
||||
>
|
||||
{children}
|
||||
</RouterContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export default RouterContextMock;
|
||||
91
apps/meteor/tests/mocks/client/ServerProviderMock.tsx
Normal file
91
apps/meteor/tests/mocks/client/ServerProviderMock.tsx
Normal file
@@ -0,0 +1,91 @@
|
||||
import type { Serialized } from '@rocket.chat/core-typings';
|
||||
import type { Method, PathPattern, OperationParams, UrlParams, OperationResult } from '@rocket.chat/rest-typings';
|
||||
import type { EndpointFunction, ServerContextValue } from '@rocket.chat/ui-contexts';
|
||||
import { ServerContext } from '@rocket.chat/ui-contexts';
|
||||
import { useMemo } from 'react';
|
||||
import type { ContextType, ReactNode } from 'react';
|
||||
|
||||
type RegisterEndpoint = <TMethod extends Method, TPathPattern extends PathPattern>(
|
||||
method: TMethod,
|
||||
pathPattern: TPathPattern,
|
||||
endpoint: EndpointFunction<TMethod, TPathPattern>,
|
||||
) => void;
|
||||
|
||||
type CallEndpoint = <TMethod extends Method, TPathPattern extends PathPattern>(args: {
|
||||
method: TMethod;
|
||||
pathPattern: TPathPattern;
|
||||
keys: UrlParams<TPathPattern>;
|
||||
params: OperationParams<TMethod, TPathPattern>;
|
||||
}) => Promise<Serialized<OperationResult<TMethod, TPathPattern>>>;
|
||||
|
||||
// this function should be used to create a new instance of `callEndpoint` to be passed to the `ServerProviderMock`
|
||||
// as the second parameter, it returns a function that can be used to register endpoint mocks
|
||||
// the rest should be self-explanatory, just rely on the types.
|
||||
export const makeCallEndpoint = (): [CallEndpoint, RegisterEndpoint] => {
|
||||
const endpoints = new Map<`${Method}/${PathPattern}`, (params: any) => Promise<unknown>>();
|
||||
|
||||
const getEndpoint = <TMethod extends Method, TPathPattern extends PathPattern>(
|
||||
method: TMethod,
|
||||
pathPattern: TPathPattern,
|
||||
): EndpointFunction<TMethod, TPathPattern> => {
|
||||
const endpoint = endpoints.get(`${method}/${pathPattern}`);
|
||||
if (!endpoint) {
|
||||
throw new Error('Endpoint not implemented');
|
||||
}
|
||||
|
||||
return endpoint as EndpointFunction<TMethod, TPathPattern>;
|
||||
};
|
||||
|
||||
const registerEndpoint: RegisterEndpoint = (method, pathPattern, endpoint) => {
|
||||
endpoints.set(`${method}/${pathPattern}`, endpoint);
|
||||
};
|
||||
|
||||
const callEndpoint: CallEndpoint = (args) => {
|
||||
const endpoint = getEndpoint(args.method, args.pathPattern);
|
||||
if (!endpoint) {
|
||||
throw new Error('Endpoint not implemented');
|
||||
}
|
||||
return endpoint(args.params);
|
||||
};
|
||||
|
||||
return [callEndpoint, registerEndpoint];
|
||||
};
|
||||
|
||||
const absoluteUrl = () => ''; // to be implemented
|
||||
const uploadToEndpoint = async () => {
|
||||
throw new Error('not implemented');
|
||||
}; // to be implemented
|
||||
const getStream = () => () => () => undefined; // to be implemented
|
||||
const getStreamAll = () => () => () => undefined; // to be implemented
|
||||
const callEndpoint = () => {
|
||||
throw new Error('not implemented');
|
||||
}; // to be implemented
|
||||
const writeStream = () => undefined; // to be implemented
|
||||
|
||||
const contextValue: ServerContextValue = {
|
||||
connected: true,
|
||||
status: 'connected',
|
||||
retryCount: 0,
|
||||
info: undefined,
|
||||
absoluteUrl,
|
||||
// callMethod,
|
||||
callEndpoint,
|
||||
uploadToEndpoint,
|
||||
getStream,
|
||||
getStreamAll,
|
||||
reconnect: () => undefined,
|
||||
disconnect: () => undefined,
|
||||
writeStream,
|
||||
};
|
||||
|
||||
export type ServerProviderMockProps = {
|
||||
children?: ReactNode;
|
||||
callEndpoint?: ContextType<typeof ServerContext>['callEndpoint'];
|
||||
};
|
||||
|
||||
const ServerProviderMock = ({ children, callEndpoint }: ServerProviderMockProps) => {
|
||||
const value = useMemo(() => ({ ...contextValue, callEndpoint: callEndpoint ?? contextValue.callEndpoint }), [callEndpoint]);
|
||||
return <ServerContext.Provider value={value}>{children}</ServerContext.Provider>;
|
||||
};
|
||||
|
||||
export default ServerProviderMock;
|
||||
47
apps/meteor/tests/mocks/client/marketplace.tsx
Normal file
47
apps/meteor/tests/mocks/client/marketplace.tsx
Normal file
@@ -0,0 +1,47 @@
|
||||
import { AppClientManager } from '@rocket.chat/apps/dist/client/AppClientManager';
|
||||
import { AppsEngineUIHost } from '@rocket.chat/apps/dist/client/AppsEngineUIHost';
|
||||
import type { IExternalComponentRoomInfo } from '@rocket.chat/apps/dist/client/definition/IExternalComponentRoomInfo';
|
||||
import type { ReactNode } from 'react';
|
||||
|
||||
import { AppsContext, type IAppsOrchestrator } from '../../../client/contexts/AppsContext';
|
||||
import { createFakeExternalComponentRoomInfo, createFakeExternalComponentUserInfo } from '../data';
|
||||
|
||||
class MockedAppsEngineUIHost extends AppsEngineUIHost {
|
||||
public async getClientRoomInfo(): Promise<IExternalComponentRoomInfo> {
|
||||
return createFakeExternalComponentRoomInfo();
|
||||
}
|
||||
|
||||
public async getClientUserInfo() {
|
||||
return createFakeExternalComponentUserInfo();
|
||||
}
|
||||
}
|
||||
|
||||
class MockedAppClientManager extends AppClientManager {}
|
||||
|
||||
export const mockAppsOrchestrator = () => {
|
||||
const appsEngineUIHost = new MockedAppsEngineUIHost();
|
||||
const manager = new MockedAppClientManager(appsEngineUIHost);
|
||||
|
||||
const orchestrator: IAppsOrchestrator = {
|
||||
load: () => Promise.resolve(),
|
||||
getAppClientManager: () => manager,
|
||||
handleError: () => undefined,
|
||||
getInstalledApps: async () => [],
|
||||
getAppsFromMarketplace: async () => ({ apps: [] }),
|
||||
getAppsOnBundle: async () => [],
|
||||
getApp: () => Promise.reject(new Error('not implemented')),
|
||||
setAppSettings: async () => undefined,
|
||||
installApp: () => Promise.reject(new Error('not implemented')),
|
||||
updateApp: () => Promise.reject(new Error('not implemented')),
|
||||
buildExternalUrl: () => Promise.reject(new Error('not implemented')),
|
||||
buildExternalAppRequest: () => Promise.reject(new Error('not implemented')),
|
||||
buildIncompatibleExternalUrl: () => Promise.reject(new Error('not implemented')),
|
||||
getCategories: () => Promise.reject(new Error('not implemented')),
|
||||
};
|
||||
|
||||
return orchestrator;
|
||||
};
|
||||
|
||||
export const mockedAppsContext = (children: ReactNode) => (
|
||||
<AppsContext.Provider value={mockAppsOrchestrator()}>{children}</AppsContext.Provider>
|
||||
);
|
||||
57
apps/meteor/tests/mocks/client/meteor.ts
Normal file
57
apps/meteor/tests/mocks/client/meteor.ts
Normal file
@@ -0,0 +1,57 @@
|
||||
import { jest } from '@jest/globals';
|
||||
|
||||
export const Meteor = {
|
||||
loginWithSamlToken: jest.fn((_token, callback: () => void) => callback()),
|
||||
connection: {
|
||||
_stream: { on: jest.fn() },
|
||||
},
|
||||
_localStorage: {
|
||||
getItem: jest.fn(),
|
||||
setItem: jest.fn(),
|
||||
},
|
||||
users: {},
|
||||
userId: () => 'uid',
|
||||
_SynchronousQueue: class _SynchronousQueue {
|
||||
drain = jest.fn();
|
||||
},
|
||||
_runFresh: jest.fn(),
|
||||
_isPromise: jest.fn(() => false),
|
||||
defer: jest.fn((fn: () => void) => queueMicrotask(fn)),
|
||||
};
|
||||
|
||||
export const Mongo = {
|
||||
Collection: class Collection {
|
||||
_collection = {
|
||||
_docs: {},
|
||||
};
|
||||
|
||||
find = jest.fn(() => ({
|
||||
fetch: jest.fn(() => []),
|
||||
observe: jest.fn(),
|
||||
}));
|
||||
|
||||
findOne = jest.fn();
|
||||
|
||||
update = jest.fn();
|
||||
},
|
||||
};
|
||||
|
||||
export const Accounts = {
|
||||
onLogin: jest.fn(),
|
||||
onLogout: jest.fn(),
|
||||
};
|
||||
|
||||
export const Tracker = { autorun: jest.fn() };
|
||||
|
||||
export const ReactiveVar = class ReactiveVar {};
|
||||
|
||||
export const EJSON = {
|
||||
isBinary: jest.fn(() => false),
|
||||
clone: jest.fn((obj) => obj),
|
||||
equals: jest.fn((a, b) => JSON.stringify(a) === JSON.stringify(b)),
|
||||
};
|
||||
|
||||
export const DDPCommon = {
|
||||
parseDDP: jest.fn((msg: string) => JSON.parse(msg)),
|
||||
stringifyDDP: jest.fn((msg: unknown) => JSON.stringify(msg)),
|
||||
};
|
||||
@@ -0,0 +1,37 @@
|
||||
import { mockAppRoot } from '@rocket.chat/mock-providers';
|
||||
|
||||
export const createRenteionPolicySettingsMock = ({
|
||||
enabled = true,
|
||||
filesOnly = false,
|
||||
doNotPrunePinned = false,
|
||||
appliesToChannels = false,
|
||||
TTLChannels = 60000,
|
||||
appliesToGroups = false,
|
||||
TTLGroups = 60000,
|
||||
appliesToDMs = false,
|
||||
TTLDMs = 60000,
|
||||
precision = '0',
|
||||
advancedPrecision = false,
|
||||
advancedPrecisionCron = '*/30 * * * *',
|
||||
} = {}) => {
|
||||
return mockAppRoot()
|
||||
.withTranslations('en', 'core', {
|
||||
RetentionPolicy_RoomWarning_NextRunDate: '{{maxAge}} {{nextRunDate}}',
|
||||
RetentionPolicy_RoomWarning_Unpinned_NextRunDate: 'Unpinned {{maxAge}} {{nextRunDate}}',
|
||||
RetentionPolicy_RoomWarning_FilesOnly_NextRunDate: 'FilesOnly {{maxAge}} {{nextRunDate}}',
|
||||
RetentionPolicy_RoomWarning_UnpinnedFilesOnly_NextRunDate: 'UnpinnedFilesOnly {{maxAge}} {{nextRunDate}}',
|
||||
})
|
||||
.withSetting('RetentionPolicy_Enabled', enabled)
|
||||
.withSetting('RetentionPolicy_FilesOnly', filesOnly)
|
||||
.withSetting('RetentionPolicy_DoNotPrunePinned', doNotPrunePinned)
|
||||
.withSetting('RetentionPolicy_AppliesToChannels', appliesToChannels)
|
||||
.withSetting('RetentionPolicy_TTL_Channels', TTLChannels)
|
||||
.withSetting('RetentionPolicy_AppliesToGroups', appliesToGroups)
|
||||
.withSetting('RetentionPolicy_TTL_Groups', TTLGroups)
|
||||
.withSetting('RetentionPolicy_AppliesToDMs', appliesToDMs)
|
||||
.withSetting('RetentionPolicy_TTL_DMs', TTLDMs)
|
||||
.withSetting('RetentionPolicy_Precision', precision)
|
||||
.withSetting('RetentionPolicy_Advanced_Precision', advancedPrecision)
|
||||
.withSetting('RetentionPolicy_Advanced_Precision_Cron', advancedPrecisionCron)
|
||||
.build();
|
||||
};
|
||||
502
apps/meteor/tests/mocks/data.ts
Normal file
502
apps/meteor/tests/mocks/data.ts
Normal file
@@ -0,0 +1,502 @@
|
||||
import { faker } from '@faker-js/faker';
|
||||
import type { IExternalComponentRoomInfo } from '@rocket.chat/apps/dist/client/definition/IExternalComponentRoomInfo';
|
||||
import type { IExternalComponentUserInfo } from '@rocket.chat/apps/dist/client/definition/IExternalComponentUserInfo';
|
||||
import type { ILivechatContact } from '@rocket.chat/apps-engine/definition/livechat';
|
||||
import {
|
||||
AppSubscriptionStatus,
|
||||
ILivechatAgentStatus,
|
||||
LivechatPriorityWeight,
|
||||
OmnichannelSourceType,
|
||||
UserStatus,
|
||||
} from '@rocket.chat/core-typings';
|
||||
import type {
|
||||
LicenseInfo,
|
||||
App,
|
||||
IMessage,
|
||||
IRoom,
|
||||
IUser,
|
||||
ILivechatContactChannel,
|
||||
Serialized,
|
||||
ILivechatAgent,
|
||||
ILivechatTag,
|
||||
IOmnichannelBusinessUnit,
|
||||
ILivechatDepartment,
|
||||
ILivechatMonitor,
|
||||
IOmnichannelRoom,
|
||||
} from '@rocket.chat/core-typings';
|
||||
import { parse } from '@rocket.chat/message-parser';
|
||||
import type { ILivechatContactWithManagerData } from '@rocket.chat/rest-typings';
|
||||
import type { SubscriptionWithRoom } from '@rocket.chat/ui-contexts';
|
||||
|
||||
import type { MessageWithMdEnforced } from '../../client/lib/parseMessageTextToAstMarkdown';
|
||||
|
||||
export function createFakeUser<TUser extends IUser>(overrides?: Partial<IUser> & Omit<TUser, keyof IUser>): TUser;
|
||||
export function createFakeUser(overrides?: Partial<IUser>): IUser {
|
||||
return {
|
||||
_id: faker.database.mongodbObjectId(),
|
||||
_updatedAt: faker.date.recent(),
|
||||
username: faker.internet.userName(),
|
||||
name: faker.person.fullName(),
|
||||
createdAt: faker.date.recent(),
|
||||
roles: ['user'],
|
||||
active: faker.datatype.boolean(),
|
||||
type: 'user',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
export const createFakeRoom = <T extends IRoom = IRoom>(overrides?: Partial<T & { retention?: { enabled: boolean } }>): T =>
|
||||
({
|
||||
_id: faker.database.mongodbObjectId(),
|
||||
_updatedAt: faker.date.recent(),
|
||||
t: faker.helpers.arrayElement(['c', 'p', 'd']),
|
||||
msgs: faker.number.int({ min: 0 }),
|
||||
u: {
|
||||
_id: faker.database.mongodbObjectId(),
|
||||
username: faker.internet.userName(),
|
||||
name: faker.person.fullName(),
|
||||
...overrides?.u,
|
||||
},
|
||||
usersCount: faker.number.int({ min: 0 }),
|
||||
autoTranslateLanguage: faker.helpers.arrayElement(['en', 'es', 'pt', 'ar', 'it', 'ru', 'fr']),
|
||||
...overrides,
|
||||
}) as T;
|
||||
|
||||
export const createFakeOmnichannelRoom = (overrides?: Partial<IOmnichannelRoom>): IOmnichannelRoom => ({
|
||||
_id: faker.database.mongodbObjectId(),
|
||||
_updatedAt: faker.date.recent(),
|
||||
t: 'l',
|
||||
msgs: faker.number.int({ min: 0 }),
|
||||
ts: faker.date.recent(),
|
||||
u: {
|
||||
_id: faker.database.mongodbObjectId(),
|
||||
username: faker.internet.userName(),
|
||||
name: faker.person.fullName(),
|
||||
...overrides?.u,
|
||||
},
|
||||
v: {
|
||||
_id: faker.database.mongodbObjectId(),
|
||||
username: faker.internet.userName(),
|
||||
name: faker.person.fullName(),
|
||||
status: UserStatus.ONLINE,
|
||||
token: faker.string.uuid(),
|
||||
activity: [],
|
||||
...overrides?.v,
|
||||
},
|
||||
source: {
|
||||
type: OmnichannelSourceType.WIDGET,
|
||||
...overrides?.source,
|
||||
},
|
||||
usersCount: faker.number.int({ min: 0 }),
|
||||
priorityWeight: LivechatPriorityWeight.NOT_SPECIFIED,
|
||||
estimatedWaitingTimeQueue: faker.number.int({ min: 0, max: 100 }),
|
||||
waitingResponse: faker.datatype.boolean(),
|
||||
livechatData: {},
|
||||
...overrides,
|
||||
});
|
||||
|
||||
export const createFakeSubscription = (overrides?: Partial<SubscriptionWithRoom>): SubscriptionWithRoom => ({
|
||||
_id: faker.database.mongodbObjectId(),
|
||||
_updatedAt: faker.date.recent(),
|
||||
u: {
|
||||
_id: faker.database.mongodbObjectId(),
|
||||
username: faker.internet.userName(),
|
||||
name: faker.person.fullName(),
|
||||
...overrides?.u,
|
||||
},
|
||||
rid: faker.database.mongodbObjectId(),
|
||||
open: faker.datatype.boolean(),
|
||||
ts: faker.date.recent(),
|
||||
name: faker.person.fullName(),
|
||||
unread: faker.number.int({ min: 0 }),
|
||||
t: faker.helpers.arrayElement(['c', 'p', 'd']),
|
||||
ls: faker.date.recent(),
|
||||
lr: faker.date.recent(),
|
||||
userMentions: faker.number.int({ min: 0 }),
|
||||
groupMentions: faker.number.int({ min: 0 }),
|
||||
lowerCaseName: faker.person.fullName().toLowerCase(),
|
||||
lowerCaseFName: faker.person.fullName().toLowerCase(),
|
||||
usersCount: faker.number.int({ min: 0 }),
|
||||
waitingResponse: faker.datatype.boolean(),
|
||||
priorityWeight: LivechatPriorityWeight.NOT_SPECIFIED,
|
||||
estimatedWaitingTimeQueue: faker.number.int({ min: 0, max: 100 }),
|
||||
livechatData: faker.date.recent(),
|
||||
...overrides,
|
||||
});
|
||||
|
||||
export function createFakeMessage<TMessage extends IMessage>(overrides?: Partial<IMessage> & Omit<TMessage, keyof IMessage>): TMessage;
|
||||
export function createFakeMessage(overrides?: Partial<IMessage>): IMessage {
|
||||
return {
|
||||
_id: faker.database.mongodbObjectId(),
|
||||
_updatedAt: faker.date.recent(),
|
||||
rid: faker.database.mongodbObjectId(),
|
||||
msg: faker.lorem.sentence(),
|
||||
ts: faker.date.recent(),
|
||||
u: {
|
||||
_id: faker.database.mongodbObjectId(),
|
||||
username: faker.internet.userName(),
|
||||
name: faker.person.fullName(),
|
||||
...overrides?.u,
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
export function createFakeMessageWithMd<TMessage extends IMessage>(
|
||||
overrides?: Partial<MessageWithMdEnforced<TMessage>>,
|
||||
): MessageWithMdEnforced<TMessage>;
|
||||
export function createFakeMessageWithMd(overrides?: Partial<MessageWithMdEnforced<IMessage>>): MessageWithMdEnforced<IMessage> {
|
||||
const fakeMessage = createFakeMessage(overrides);
|
||||
|
||||
return {
|
||||
...fakeMessage,
|
||||
md: parse(fakeMessage.msg),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
export function createFakeApp(partialApp: Partial<App> = {}): App {
|
||||
const appId = faker.database.mongodbObjectId();
|
||||
|
||||
const app: App = {
|
||||
id: appId,
|
||||
iconFileData: faker.image.dataUri(),
|
||||
name: faker.commerce.productName(),
|
||||
appRequestStats: {
|
||||
appId: partialApp.id ?? appId,
|
||||
totalSeen: faker.number.int({ min: 0, max: 100 }),
|
||||
totalUnseen: faker.number.int({ min: 0, max: 100 }),
|
||||
},
|
||||
author: {
|
||||
name: faker.company.name(),
|
||||
homepage: faker.internet.url(),
|
||||
support: faker.internet.email(),
|
||||
},
|
||||
description: faker.lorem.paragraph(),
|
||||
shortDescription: faker.lorem.sentence(),
|
||||
privacyPolicySummary: faker.lorem.sentence(),
|
||||
detailedDescription: {
|
||||
raw: faker.lorem.paragraph(),
|
||||
rendered: faker.lorem.paragraph(),
|
||||
},
|
||||
detailedChangelog: {
|
||||
raw: faker.lorem.paragraph(),
|
||||
rendered: faker.lorem.paragraph(),
|
||||
},
|
||||
categories: [],
|
||||
version: faker.system.semver(),
|
||||
versionIncompatible: faker.datatype.boolean(),
|
||||
price: faker.number.float({ min: 0, max: 1000 }),
|
||||
purchaseType: faker.helpers.arrayElement(['buy', 'subscription']),
|
||||
pricingPlans: [],
|
||||
iconFileContent: faker.image.dataUri(),
|
||||
isSubscribed: faker.datatype.boolean(),
|
||||
bundledIn: [],
|
||||
marketplaceVersion: faker.system.semver(),
|
||||
get latest() {
|
||||
return app;
|
||||
},
|
||||
subscriptionInfo: {
|
||||
typeOf: faker.lorem.word(),
|
||||
status: faker.helpers.enumValue(AppSubscriptionStatus),
|
||||
statusFromBilling: faker.datatype.boolean(),
|
||||
isSeatBased: faker.datatype.boolean(),
|
||||
seats: faker.number.int({ min: 0, max: 50 }),
|
||||
maxSeats: faker.number.int({ min: 50, max: 100 }),
|
||||
license: {
|
||||
license: faker.lorem.word(),
|
||||
version: faker.number.int({ min: 0, max: 3 }),
|
||||
expireDate: faker.date.future().toISOString(),
|
||||
},
|
||||
startDate: faker.date.past().toISOString(),
|
||||
periodEnd: faker.date.future().toISOString(),
|
||||
endDate: faker.date.future().toISOString(),
|
||||
isSubscribedViaBundle: faker.datatype.boolean(),
|
||||
},
|
||||
tosLink: faker.internet.url(),
|
||||
privacyLink: faker.internet.url(),
|
||||
modifiedAt: faker.date.recent().toISOString(),
|
||||
permissions: faker.helpers.multiple(() => ({
|
||||
name: faker.hacker.verb(),
|
||||
required: faker.datatype.boolean(),
|
||||
})),
|
||||
languages: faker.helpers.multiple(() => faker.location.countryCode()),
|
||||
createdDate: faker.date.past().toISOString(),
|
||||
private: faker.datatype.boolean(),
|
||||
documentationUrl: faker.internet.url(),
|
||||
migrated: faker.datatype.boolean(),
|
||||
...partialApp,
|
||||
};
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
export const createFakeExternalComponentUserInfo = (partial: Partial<IExternalComponentUserInfo> = {}): IExternalComponentUserInfo => ({
|
||||
id: faker.database.mongodbObjectId(),
|
||||
username: faker.internet.userName(),
|
||||
avatarUrl: faker.image.avatar(),
|
||||
...partial,
|
||||
});
|
||||
|
||||
export const createFakeExternalComponentRoomInfo = (partial: Partial<IExternalComponentRoomInfo> = {}): IExternalComponentRoomInfo => ({
|
||||
id: faker.database.mongodbObjectId(),
|
||||
members: faker.helpers.multiple(createFakeExternalComponentUserInfo),
|
||||
slugifiedName: faker.lorem.slug(),
|
||||
...partial,
|
||||
});
|
||||
|
||||
export const createFakeLicenseInfo = (partial: Partial<Omit<LicenseInfo, 'license'>> = {}): Omit<LicenseInfo, 'license'> => ({
|
||||
activeModules: faker.helpers.arrayElements([
|
||||
'auditing',
|
||||
'canned-responses',
|
||||
'ldap-enterprise',
|
||||
'livechat-enterprise',
|
||||
'voip-enterprise',
|
||||
'omnichannel-mobile-enterprise',
|
||||
'engagement-dashboard',
|
||||
'push-privacy',
|
||||
'scalability',
|
||||
'teams-mention',
|
||||
'saml-enterprise',
|
||||
'oauth-enterprise',
|
||||
'device-management',
|
||||
'federation',
|
||||
'videoconference-enterprise',
|
||||
'message-read-receipt',
|
||||
'outlook-calendar',
|
||||
'hide-watermark',
|
||||
'custom-roles',
|
||||
'accessibility-certification',
|
||||
'outbound-messaging',
|
||||
'abac',
|
||||
]),
|
||||
externalModules: [],
|
||||
preventedActions: {
|
||||
activeUsers: faker.datatype.boolean(),
|
||||
guestUsers: faker.datatype.boolean(),
|
||||
roomsPerGuest: faker.datatype.boolean(),
|
||||
privateApps: faker.datatype.boolean(),
|
||||
marketplaceApps: faker.datatype.boolean(),
|
||||
monthlyActiveContacts: faker.datatype.boolean(),
|
||||
},
|
||||
limits: {
|
||||
activeUsers: { value: faker.number.int({ min: 0 }), max: faker.number.int({ min: 0 }) },
|
||||
guestUsers: { value: faker.number.int({ min: 0 }), max: faker.number.int({ min: 0 }) },
|
||||
roomsPerGuest: { value: faker.number.int({ min: 0 }), max: faker.number.int({ min: 0 }) },
|
||||
privateApps: { value: faker.number.int({ min: 0 }), max: faker.number.int({ min: 0 }) },
|
||||
marketplaceApps: { value: faker.number.int({ min: 0 }), max: faker.number.int({ min: 0 }) },
|
||||
monthlyActiveContacts: { value: faker.number.int({ min: 0 }), max: faker.number.int({ min: 0 }) },
|
||||
},
|
||||
tags: faker.helpers.multiple(() => ({
|
||||
name: faker.commerce.productAdjective(),
|
||||
color: faker.internet.color(),
|
||||
})),
|
||||
trial: faker.datatype.boolean(),
|
||||
hasValidLicense: faker.datatype.boolean(),
|
||||
...partial,
|
||||
});
|
||||
|
||||
export function createFakeMessageWithAttachment<TMessage extends IMessage>(overrides?: Partial<TMessage>): TMessage;
|
||||
export function createFakeMessageWithAttachment(overrides?: Partial<IMessage>): IMessage {
|
||||
const fakeMessage = createFakeMessage(overrides);
|
||||
const fileId = faker.database.mongodbObjectId();
|
||||
const fileName = faker.system.commonFileName('txt');
|
||||
|
||||
return {
|
||||
...fakeMessage,
|
||||
msg: '',
|
||||
file: {
|
||||
_id: fileId,
|
||||
name: fileName,
|
||||
type: 'text/plain',
|
||||
size: faker.number.int(),
|
||||
format: faker.string.alpha(),
|
||||
},
|
||||
attachments: [
|
||||
{
|
||||
type: 'file',
|
||||
title: fileName,
|
||||
title_link: `/file-upload/${fileId}/${fileName}`,
|
||||
},
|
||||
],
|
||||
files: [
|
||||
{
|
||||
_id: fileId,
|
||||
name: fileName,
|
||||
type: 'text/plain',
|
||||
size: faker.number.int(),
|
||||
format: faker.string.alpha(),
|
||||
},
|
||||
],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
const guestNames = faker.helpers.uniqueArray(faker.person.firstName, 1000);
|
||||
|
||||
function pullNextVisitorName() {
|
||||
const guestName = guestNames.pop();
|
||||
|
||||
if (!guestName) {
|
||||
throw new Error('exhausted guest names');
|
||||
}
|
||||
|
||||
return guestName;
|
||||
}
|
||||
|
||||
export function createFakeVisitor() {
|
||||
return {
|
||||
name: pullNextVisitorName(),
|
||||
email: faker.internet.email(),
|
||||
} as const;
|
||||
}
|
||||
|
||||
export function createFakeContactChannel(overrides?: Partial<Serialized<ILivechatContactChannel>>): Serialized<ILivechatContactChannel> {
|
||||
return {
|
||||
name: 'widget',
|
||||
blocked: false,
|
||||
verified: false,
|
||||
...overrides,
|
||||
visitor: {
|
||||
visitorId: faker.string.uuid(),
|
||||
source: {
|
||||
type: OmnichannelSourceType.WIDGET,
|
||||
},
|
||||
...overrides?.visitor,
|
||||
},
|
||||
details: {
|
||||
type: OmnichannelSourceType.WIDGET,
|
||||
destination: '',
|
||||
...overrides?.details,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function createFakeContact(overrides?: Partial<Serialized<ILivechatContact>>): Serialized<ILivechatContact> {
|
||||
return {
|
||||
_id: faker.string.uuid(),
|
||||
_updatedAt: new Date().toISOString(),
|
||||
name: pullNextVisitorName(),
|
||||
phones: [{ phoneNumber: faker.phone.number() }],
|
||||
emails: [{ address: faker.internet.email() }],
|
||||
unknown: true,
|
||||
channels: [createFakeContactChannel()],
|
||||
createdAt: new Date().toISOString(),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
export function createFakeContactWithManagerData(
|
||||
overrides?: Partial<Serialized<ILivechatContactWithManagerData>>,
|
||||
): Serialized<ILivechatContactWithManagerData> {
|
||||
const { contactManager: contactManagerOverwrites, ...contactOverwrites } = overrides || {};
|
||||
const contact = createFakeContact(contactOverwrites);
|
||||
return {
|
||||
...contact,
|
||||
contactManager: {
|
||||
_id: faker.string.uuid(),
|
||||
name: faker.person.fullName(),
|
||||
username: faker.internet.userName(),
|
||||
...contactManagerOverwrites,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function createFakeAgent(overrides?: Partial<Serialized<ILivechatAgent>>): Serialized<ILivechatAgent> {
|
||||
const email = faker.internet.email();
|
||||
const firstName = faker.person.firstName();
|
||||
const lastName = faker.person.lastName();
|
||||
const username = faker.internet.userName({ firstName, lastName });
|
||||
|
||||
return {
|
||||
_id: faker.string.uuid(),
|
||||
username,
|
||||
status: UserStatus.ONLINE,
|
||||
statusLivechat: ILivechatAgentStatus.AVAILABLE,
|
||||
name: `${firstName} ${lastName}`,
|
||||
emails: [
|
||||
{
|
||||
address: email,
|
||||
verified: false,
|
||||
},
|
||||
],
|
||||
livechat: {
|
||||
maxNumberSimultaneousChat: 0,
|
||||
},
|
||||
lastRoutingTime: '',
|
||||
livechatCount: 0,
|
||||
active: true,
|
||||
createdAt: new Date().toISOString(),
|
||||
_updatedAt: new Date().toISOString(),
|
||||
roles: [],
|
||||
type: '',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
export function createFakeTag(overrides?: Partial<Serialized<ILivechatTag>>): Serialized<ILivechatTag> {
|
||||
return {
|
||||
_id: faker.string.uuid(),
|
||||
name: faker.commerce.department(),
|
||||
description: 'description',
|
||||
numDepartments: 0,
|
||||
departments: [],
|
||||
_updatedAt: new Date().toISOString(),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
export function createFakeBusinessUnit(overrides?: Partial<Serialized<IOmnichannelBusinessUnit>>): Serialized<IOmnichannelBusinessUnit> {
|
||||
return {
|
||||
_id: faker.string.uuid(),
|
||||
name: faker.commerce.department(),
|
||||
visibility: 'public',
|
||||
type: 'u',
|
||||
numMonitors: 1,
|
||||
numDepartments: 1,
|
||||
_updatedAt: new Date().toISOString(),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
export const createFakeDepartment = (overrides: Partial<Serialized<ILivechatDepartment>> = {}): Serialized<ILivechatDepartment> => ({
|
||||
_id: faker.string.uuid(),
|
||||
name: `${faker.commerce.department()} ${faker.string.uuid()}`,
|
||||
enabled: true,
|
||||
email: faker.internet.email(),
|
||||
showOnRegistration: false,
|
||||
showOnOfflineForm: false,
|
||||
type: 'd',
|
||||
_updatedAt: new Date().toISOString(),
|
||||
offlineMessageChannelName: '',
|
||||
numAgents: 0,
|
||||
ancestors: undefined,
|
||||
parentId: undefined,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
export function createFakeMonitor(overrides?: Partial<Serialized<ILivechatMonitor>>): Serialized<ILivechatMonitor> {
|
||||
const firstName = faker.person.firstName();
|
||||
const lastName = faker.person.lastName();
|
||||
const username = faker.internet.userName({ firstName, lastName });
|
||||
|
||||
return {
|
||||
_id: faker.string.uuid(),
|
||||
username,
|
||||
name: `${firstName} ${lastName}`,
|
||||
type: '',
|
||||
enabled: true,
|
||||
numMonitors: 0,
|
||||
visibility: 'visible',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
export const createMockedPagination = (results = 0, total = 0) => ({
|
||||
current: 0,
|
||||
setCurrent: () => undefined,
|
||||
itemsPerPage: 25 as const,
|
||||
setItemsPerPage: () => undefined,
|
||||
itemsPerPageLabel: () => 'Items per page:',
|
||||
showingResultsLabel: () => `Showing results 1 - ${results} of ${total}`,
|
||||
});
|
||||
BIN
apps/meteor/tests/mocks/files/audio_mock.mp3
Normal file
BIN
apps/meteor/tests/mocks/files/audio_mock.mp3
Normal file
Binary file not shown.
13
apps/meteor/tests/mocks/files/diagram.drawio
Normal file
13
apps/meteor/tests/mocks/files/diagram.drawio
Normal file
@@ -0,0 +1,13 @@
|
||||
<mxfile host="app.diagrams.net" modified="2024-05-21T16:10:09.295Z" agent="Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36" etag="ZxZRCTHi-kxhlzk7b9_Z" version="24.4.4" type="device">
|
||||
<diagram name="Página-1" id="9eBILa8281JaQ4yUkDbp">
|
||||
<mxGraphModel dx="1434" dy="786" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="827" pageHeight="1169" math="0" shadow="0">
|
||||
<root>
|
||||
<mxCell id="0" />
|
||||
<mxCell id="1" parent="0" />
|
||||
<mxCell id="dopCU4gkJe7Sfp6IDYO1-1" value="<b><font style="font-size: 30px;">Rocket.Chat</font></b>" style="text;html=1;align=center;verticalAlign=middle;resizable=0;points=[];autosize=1;strokeColor=none;fillColor=none;" vertex="1" parent="1">
|
||||
<mxGeometry x="314" y="350" width="200" height="50" as="geometry" />
|
||||
</mxCell>
|
||||
</root>
|
||||
</mxGraphModel>
|
||||
</diagram>
|
||||
</mxfile>
|
||||
BIN
apps/meteor/tests/mocks/files/exif-orientation-6.jpg
Normal file
BIN
apps/meteor/tests/mocks/files/exif-orientation-6.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 18 KiB |
BIN
apps/meteor/tests/mocks/files/sample-jpeg.jpg
Normal file
BIN
apps/meteor/tests/mocks/files/sample-jpeg.jpg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 81 KiB |
BIN
apps/meteor/tests/mocks/files/sample-tiff.tiff
Normal file
BIN
apps/meteor/tests/mocks/files/sample-tiff.tiff
Normal file
Binary file not shown.
41
apps/meteor/tests/mocks/server/BrokerMocked.ts
Normal file
41
apps/meteor/tests/mocks/server/BrokerMocked.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
export class BrokerMocked {
|
||||
actions: Record<string, (...params: unknown[]) => Promise<unknown>> = {};
|
||||
|
||||
services: Map<string, any> = new Map();
|
||||
|
||||
async destroyService(name: string): Promise<void> {
|
||||
this.services.delete(name);
|
||||
}
|
||||
|
||||
createService(instance: any): void {
|
||||
this.services.set(instance.name, instance);
|
||||
}
|
||||
|
||||
async call(method: string, data: any): Promise<any> {
|
||||
return this.actions[method](data);
|
||||
}
|
||||
|
||||
async broadcastToServices(): Promise<void> {
|
||||
// no op
|
||||
}
|
||||
|
||||
async broadcast(): Promise<void> {
|
||||
// no op
|
||||
}
|
||||
|
||||
async broadcastLocal(): Promise<void> {
|
||||
// no op
|
||||
}
|
||||
|
||||
async nodeList(): Promise<any> {
|
||||
// no op
|
||||
}
|
||||
|
||||
async start(): Promise<void> {
|
||||
// no op
|
||||
}
|
||||
|
||||
mockServices(actions: Record<string, () => Promise<unknown>>) {
|
||||
this.actions = actions;
|
||||
}
|
||||
}
|
||||
10
apps/meteor/tests/mocks/server/mongodb.ts
Normal file
10
apps/meteor/tests/mocks/server/mongodb.ts
Normal file
@@ -0,0 +1,10 @@
|
||||
import proxyquire from 'proxyquire';
|
||||
|
||||
proxyquire.noCallThru().load('mongodb', {
|
||||
ObjectId: class ObjectId {
|
||||
toHexString(): string {
|
||||
return 'hexString';
|
||||
}
|
||||
},
|
||||
global: true,
|
||||
});
|
||||
25
apps/meteor/tests/mocks/utils/FakeResponse.ts
Normal file
25
apps/meteor/tests/mocks/utils/FakeResponse.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
export class FakeResponse {
|
||||
private _body: string;
|
||||
|
||||
status: number;
|
||||
|
||||
headers: Record<string, string>;
|
||||
|
||||
constructor(body: string, init: { status?: number; headers?: Record<string, string> } = {}) {
|
||||
this._body = body;
|
||||
this.status = init.status ?? 200;
|
||||
this.headers = init.headers ?? {};
|
||||
}
|
||||
|
||||
get ok() {
|
||||
return this.status >= 200 && this.status < 300;
|
||||
}
|
||||
|
||||
async json() {
|
||||
return JSON.parse(this._body);
|
||||
}
|
||||
|
||||
async text() {
|
||||
return this._body;
|
||||
}
|
||||
}
|
||||
19
apps/meteor/tests/mocks/utils/createDeferredMockFn.ts
Normal file
19
apps/meteor/tests/mocks/utils/createDeferredMockFn.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
export function createDeferredPromise<R = void>() {
|
||||
let resolve!: (value: R | PromiseLike<R>) => void;
|
||||
let reject!: (reason?: unknown) => void;
|
||||
|
||||
const promise = new Promise<R>((res, rej) => {
|
||||
resolve = res;
|
||||
reject = rej;
|
||||
});
|
||||
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
function createDeferredMockFn<R = void>() {
|
||||
const deferred = createDeferredPromise<R>();
|
||||
const fn = jest.fn(() => deferred.promise);
|
||||
return { ...deferred, fn };
|
||||
}
|
||||
|
||||
export default createDeferredMockFn;
|
||||
8
apps/meteor/tests/mocks/utils/createMockGlobalStore.ts
Normal file
8
apps/meteor/tests/mocks/utils/createMockGlobalStore.ts
Normal file
@@ -0,0 +1,8 @@
|
||||
export function createMockGlobalStore(records: any[]) {
|
||||
return {
|
||||
use: (selector: any) => selector(records),
|
||||
get state() {
|
||||
return records;
|
||||
},
|
||||
};
|
||||
}
|
||||
11
apps/meteor/tests/mocks/utils/index.ts
Normal file
11
apps/meteor/tests/mocks/utils/index.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
export { createMockGlobalStore } from './createMockGlobalStore';
|
||||
|
||||
export const emptyUnread = {
|
||||
userMentions: 0,
|
||||
groupMentions: 0,
|
||||
unread: 0,
|
||||
tunread: undefined,
|
||||
tunreadUser: undefined,
|
||||
tunreadGroup: undefined,
|
||||
alert: false,
|
||||
};
|
||||
31
apps/meteor/tests/mocks/utils/video-conference.ts
Normal file
31
apps/meteor/tests/mocks/utils/video-conference.ts
Normal file
@@ -0,0 +1,31 @@
|
||||
import { faker } from '@faker-js/faker';
|
||||
import type { IRoom, VideoConferenceType } from '@rocket.chat/core-typings';
|
||||
|
||||
const callId = faker.database.mongodbObjectId();
|
||||
const uid = faker.database.mongodbObjectId();
|
||||
|
||||
export function createFakeVideoConfCall({ type, rid }: { type: VideoConferenceType; rid: IRoom['_id'] }) {
|
||||
return {
|
||||
type,
|
||||
rid,
|
||||
_id: callId,
|
||||
status: 0,
|
||||
createdBy: {
|
||||
_id: uid,
|
||||
username: faker.internet.userName(),
|
||||
name: faker.person.fullName(),
|
||||
},
|
||||
_updatedAt: faker.date.recent(),
|
||||
createdAt: faker.date.recent(),
|
||||
providerName: faker.company.name(),
|
||||
};
|
||||
}
|
||||
|
||||
export function createFakeIncomingCall({ rid }: { rid: IRoom['_id'] }) {
|
||||
return {
|
||||
rid,
|
||||
uid,
|
||||
callId,
|
||||
dismissed: false,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user