mattermost-mobile-upstream/app/actions/websocket/users.test.ts
Pablo Vélez 7df4a0ab97
Some checks are pending
ci / lint-typecheck (push) Waiting to run
ci / detox-lint-typecheck (push) Waiting to run
ci / test (push) Waiting to run
Mm 68219 show placeholder for redacted files (#9719)
* MM-68219 - Add redacted files placeholder and related functionality

* add feature flag control and e2e tests

* adjust placeholder design, polish code, fix permalink preview issue

* polish code and add missing test

* use import path with right path

* gate post refetch behind the feature flag, refetch the open thread and avoid observeCount

* restore filesInfo for the permalink files prop added upstream

* fix stale redaction on background servers, consume the flag on every fetch path and share the viewport emitter

* replace the in-memory redaction flag with a persisted per-post epoch so ABAC file decisions survive restarts and stale posts stay hidden

* raise the redaction epoch on every resync, capture the epoch counter, only invalidate channels on role changes, and store the newer epoch when a re-verified post is otherwise unchanged

* store superseded responses unverified instead of dropping them, keep the since-fetch when re-verifying, verify permalink embeds against the linked channel, and capture the websocket epoch on arrival

* nvalidate file decisions when a user attribute field changes or all its values are cleared

* batch channel invalidations, close file viewers only when affected, reset the epoch on unstamped redaction changes, and only  re-verify the newest page's attachment posts

* re-check older channel posts a page at a time instead of one request per post

* skip the unstamped epoch lookup for posts with no files, redacted count or permalink

* keep the attribute-view retry after later invalidations, retry linked posts unless refused for the current epoch, and stop older payloads from rolling back edits via the redaction check

* MM-70905 - disable and grey out the attachment button when an ABAC pe… (#10195)

* MM-70905 - disable and grey out the attachment button when an ABAC permission policy denies uploads in the channel

* only back off render permission fetches when the server request fails, and log other errors without retrying

* remove the disableServer helper and have removeServer do both steps

* split defaultAllowed into allowWhenUnenforced and allowWhenNotEvaluated, and treat render permissions as unenforced  on servers without the decisions API

* MM-69627: Add playbook task requirements support on mobile (#10035)

* MM-69627: Add playbook task requirements support on mobile

Allow filling required task fields when checking off checklist items during
a run, gated by the same Playbooks beta setting used on web.

Co-authored-by: Cursor <cursoragent@cursor.com>

* MM-69627: Address PR review feedback for task requirements

Propagate settings write failures, harden fill-requirements save/title handling, and add missing unit coverage.

Co-authored-by: Cursor <cursoragent@cursor.com>

* MM-69627: Fix TypeScript errors in new unit tests

Co-authored-by: Cursor <cursoragent@cursor.com>

* MM-69627: Use defineMessages for fill requirements titles

Keep i18n extraction able to find the header titles after moving them to the route.

Co-authored-by: Cursor <cursoragent@cursor.com>

* MM-69627: Address review feedback for task requirements

Update checklist items locally when saving requirement values instead of
refetching the run, add missing query/navigation tests, and apply small
callback/reduce cleanups from review.

Co-authored-by: Cursor <cursoragent@cursor.com>

* MM-69627: Fix task requirements review follow-ups

Propagate local checklist write failures, clear a stale task-requirements
flag when playbooks is unsupported, and cap fill values at the desktop/
server max length.

Co-authored-by: Cursor <cursoragent@cursor.com>

* MM-69627: Move requirement field into its own component

Keep one component per file on the fill-requirements screen.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>

* MM-69122: Add file element support to interactive dialogs (#9898)

* Implement Interactive Dialog - file upload

* update demo plugin version for e2etests

* fix and add e2etests

* review fixes

* Fix version bump checkout when a tag shares the branch name (#10229)

* Fix Android crashes caused by animated custom emoji (#10030)

* Route GIF decoding through Glide

- Keep APNG4Android for APNG, animated WebP, and animated AVIF support.
- Prepend Glide's GIF decoders to avoid APNG4Android's native GIF overflow.

* Clear Expo image resources with Glide targets

- Detach drawables when Glide clears their custom target.
- Prevent recycled GIF frame resources from remaining attached to Expo image views.

* Preserve foreground image during GIF target recycling

---------

Co-authored-by: Asaad Mahmood <asaadmahmood@users.noreply.github.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Scott Bishel <scott.bishel@mattermost.com>
Co-authored-by: Nuno Simões <nuno.simoes@mattermost.com>
Co-authored-by: MangelSpec <74370284+MangelSpec@users.noreply.github.com>

* detox - fix clobbering of feature flags that cause failures in other suites.  Also small fix of a incorrectly set test-id

---------

Co-authored-by: Asaad Mahmood <asaadmahmood@users.noreply.github.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Scott Bishel <scott.bishel@mattermost.com>
Co-authored-by: Nuno Simões <nuno.simoes@mattermost.com>
Co-authored-by: MangelSpec <74370284+MangelSpec@users.noreply.github.com>
Co-authored-by: Nate Schlossberg <nate.schlossberg@mattermost.com>
2026-10-15 15:59:13 -07:00

665 lines
25 KiB
TypeScript

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {DeviceEventEmitter} from 'react-native';
import {updateChannelsDisplayName} from '@actions/local/channel';
import {RedactionInvalidationReason} from '@actions/local/redaction';
import {setCurrentUserStatus} from '@actions/local/user';
import {fetchMe, fetchUsersByIds} from '@actions/remote/user';
import {invalidateRedactionForCurrentUser} from '@actions/websocket/access_control';
import {Events, WebsocketEvents} from '@constants';
import DatabaseManager from '@database/manager';
import SessionAttributesManager from '@managers/session_attributes_manager';
import WebsocketManager from '@managers/websocket_manager';
import {queryChannelsByTypes, queryUserChannelsByTypes} from '@queries/servers/channel';
import {deleteCustomProfileAttributesByFieldId} from '@queries/servers/custom_profile';
import {queryDisplayNamePreferences} from '@queries/servers/preference';
import {getConfig, getLicense} from '@queries/servers/system';
import {getCurrentUser} from '@queries/servers/user';
import TestHelper from '@test/test_helper';
import * as logUtils from '@utils/log';
import {
handleUserUpdatedEvent,
handleUserTypingEvent,
handleStatusChangedEvent,
userTyping,
handleCustomProfileAttributesValuesUpdatedEvent,
handleCustomProfileAttributesFieldUpdatedEvent,
handleCustomProfileAttributesFieldDeletedEvent,
handleSessionAttributesPropertyFieldEvent,
} from './users';
import type ServerDataOperator from '@database/operator/server_data_operator';
jest.mock('@actions/local/channel');
jest.mock('@actions/local/user');
jest.mock('@actions/websocket/access_control');
jest.mock('@actions/remote/user');
jest.mock('@database/manager');
jest.mock('@helpers/api/preference');
jest.mock('@managers/websocket_manager');
jest.mock('@managers/session_attributes_manager', () => ({
__esModule: true,
default: {
refreshManifest: jest.fn().mockResolvedValue(undefined),
upsertManifestField: jest.fn(),
removeManifestField: jest.fn(),
},
}));
jest.mock('@queries/servers/channel');
jest.mock('@queries/servers/custom_profile');
jest.mock('@queries/servers/preference');
jest.mock('@queries/servers/system');
jest.mock('@queries/servers/user');
describe('WebSocket Users Actions', () => {
const serverUrl = 'baseHandler.test.com';
const currentUserId = 'current-user-id';
const otherUserId = 'other-user-id';
let operator: ServerDataOperator;
let batchRecords: jest.SpyInstance;
let handleUsers: jest.SpyInstance;
beforeEach(async () => {
jest.clearAllMocks();
jest.spyOn(DeviceEventEmitter, 'emit');
await DatabaseManager.init([serverUrl]);
operator = DatabaseManager.serverDatabases[serverUrl]!.operator;
jest.mocked(queryChannelsByTypes).mockReturnValue(TestHelper.fakeQuery([]));
DatabaseManager.getActiveServerUrl = jest.fn().mockResolvedValue(serverUrl);
batchRecords = jest.spyOn(operator, 'batchRecords').mockResolvedValue();
handleUsers = jest.spyOn(operator, 'handleUsers').mockResolvedValue([TestHelper.fakeUserModel({id: 'user1'})]);
});
afterEach(async () => {
await DatabaseManager.destroyServerDatabase(serverUrl);
jest.restoreAllMocks();
});
describe('handleUserUpdatedEvent', () => {
it('should handle missing operator', async () => {
DatabaseManager.serverDatabases = {};
const msg = {
data: {
user: {id: currentUserId},
},
} as WebSocketMessage;
await handleUserUpdatedEvent(serverUrl, msg);
expect(handleUsers).not.toHaveBeenCalled();
});
it('should handle missing current user', async () => {
jest.mocked(getCurrentUser).mockResolvedValue(undefined);
const msg = {
data: {
user: {id: currentUserId},
},
} as WebSocketMessage;
await handleUserUpdatedEvent(serverUrl, msg);
expect(handleUsers).not.toHaveBeenCalled();
});
it('should handle current user update', async () => {
const mockUser = TestHelper.fakeUser({
id: currentUserId,
update_at: 1234,
notify_props: TestHelper.fakeUserNotifyProps({email: 'true'}),
});
const mockCurrentUser = TestHelper.fakeUserModel({
id: currentUserId,
updateAt: 1000,
locale: 'en',
});
jest.mocked(getCurrentUser).mockResolvedValue(mockCurrentUser);
jest.mocked(fetchMe).mockResolvedValue({user: mockUser});
const msg = {
data: {
user: mockUser,
},
} as WebSocketMessage;
await handleUserUpdatedEvent(serverUrl, msg);
expect(handleUsers).toHaveBeenCalled();
expect(batchRecords).toHaveBeenCalled();
});
it('should invalidate file decisions only when an ABAC subject field of the current user changes', async () => {
// A nickname edit or a reordered role list must not invalidate every cached decision.
const mockCurrentUser = TestHelper.fakeUserModel({id: currentUserId, updateAt: 1000, locale: 'en', email: 'me@example.com', roles: 'system_user system_admin'});
jest.mocked(getCurrentUser).mockResolvedValue(mockCurrentUser);
const cosmetic = TestHelper.fakeUser({id: currentUserId, update_at: 1234, locale: 'en', email: 'me@example.com', roles: 'system_admin system_user', nickname: 'new'});
jest.mocked(fetchMe).mockResolvedValue({user: cosmetic});
await handleUserUpdatedEvent(serverUrl, {data: {user: cosmetic}} as WebSocketMessage);
expect(invalidateRedactionForCurrentUser).not.toHaveBeenCalled();
const demoted = {...cosmetic, roles: 'system_user'};
jest.mocked(fetchMe).mockResolvedValue({user: demoted});
await handleUserUpdatedEvent(serverUrl, {data: {user: demoted}} as WebSocketMessage);
expect(invalidateRedactionForCurrentUser).toHaveBeenCalledWith(serverUrl, RedactionInvalidationReason.UserFields);
});
it('should handle other user update', async () => {
const mockUser = TestHelper.fakeUser({
id: otherUserId,
update_at: 1234,
});
const mockCurrentUser = TestHelper.fakeUserModel({
id: currentUserId,
updateAt: 1000,
});
jest.mocked(getCurrentUser).mockResolvedValue(mockCurrentUser);
jest.mocked(queryUserChannelsByTypes).mockReturnValue(
TestHelper.fakeQuery([TestHelper.fakeChannelModel({id: 'channel-1'})]));
jest.mocked(updateChannelsDisplayName).mockResolvedValue({models: []});
handleUsers.mockResolvedValue([TestHelper.fakeUserModel({id: 'model-1'})]);
const msg = {
data: {
user: mockUser,
},
} as WebSocketMessage;
await handleUserUpdatedEvent(serverUrl, msg);
expect(handleUsers).toHaveBeenCalledWith({
users: [mockUser],
prepareRecordsOnly: true,
});
});
});
describe('handleUserTypingEvent', () => {
it('should handle different active server', async () => {
DatabaseManager.getActiveServerUrl = jest.fn().mockResolvedValue('different-server');
const msg = {
data: {
user_id: otherUserId,
},
broadcast: {
channel_id: 'channel-id',
},
} as WebSocketMessage;
await handleUserTypingEvent(serverUrl, msg);
expect(jest.mocked(DeviceEventEmitter.emit)).not.toHaveBeenCalled();
});
it('should handle missing database', async () => {
DatabaseManager.serverDatabases = {};
const msg = {
data: {
user_id: otherUserId,
},
broadcast: {
channel_id: 'channel-id',
},
} as WebSocketMessage;
await handleUserTypingEvent(serverUrl, msg);
expect(jest.mocked(DeviceEventEmitter.emit)).not.toHaveBeenCalled();
});
it('should handle missing user', async () => {
jest.mocked(getConfig).mockResolvedValue({
LockTeammateNameDisplay: 'false',
TeammateNameDisplay: 'username',
TimeBetweenUserTypingUpdatesMilliseconds: '500',
} as any);
jest.mocked(fetchUsersByIds).mockResolvedValue({
users: [],
existingUsers: [],
});
const msg = {
data: {
user_id: otherUserId,
},
broadcast: {
channel_id: 'channel-id',
},
} as WebSocketMessage;
jest.useFakeTimers();
const promise = handleUserTypingEvent(serverUrl, msg);
jest.runAllTimers();
jest.useRealTimers();
await promise;
expect(DeviceEventEmitter.emit).toHaveBeenCalledWith(Events.USER_TYPING, expect.any(Object));
});
it('should emit typing events', async () => {
jest.spyOn(DeviceEventEmitter, 'emit');
const channelId = 'channel-id';
const mockConfig = {
TimeBetweenUserTypingUpdatesMilliseconds: '500',
};
jest.mocked(getConfig).mockResolvedValue(mockConfig as any);
jest.mocked(fetchUsersByIds).mockResolvedValue({
users: [
TestHelper.fakeUser({
id: otherUserId,
username: 'other-user',
}),
],
existingUsers: [],
});
jest.mocked(queryDisplayNamePreferences).mockReturnValue(
TestHelper.fakeQuery([
TestHelper.fakePreferenceModel({
value: 'full_name',
}),
]),
);
jest.mocked(getLicense).mockResolvedValue({} as ClientLicense);
const msg = {
data: {
user_id: otherUserId,
parent_id: 'root-id',
},
broadcast: {
channel_id: channelId,
},
} as WebSocketMessage;
jest.useFakeTimers();
const promise = handleUserTypingEvent(serverUrl, msg);
jest.runAllTimers();
jest.useRealTimers();
await promise;
expect(DeviceEventEmitter.emit).toHaveBeenCalledWith(Events.USER_TYPING, expect.any(Object));
expect(DeviceEventEmitter.emit).toHaveBeenCalledWith(Events.USER_STOP_TYPING, expect.any(Object));
});
});
describe('userTyping', () => {
it('should send typing event', async () => {
const mockClient = {
sendUserTypingEvent: jest.fn(),
};
jest.mocked(WebsocketManager.getClient).mockReturnValue(mockClient as any);
await userTyping(serverUrl, 'channel-id', 'root-id');
expect(mockClient.sendUserTypingEvent).toHaveBeenCalledWith('channel-id', 'root-id');
});
it('should handle missing client', async () => {
jest.mocked(WebsocketManager.getClient).mockReturnValue(undefined);
await userTyping(serverUrl, 'channel-id');
// Should not throw
});
});
describe('handleStatusChangedEvent', () => {
it('should update user status', async () => {
const msg = {
data: {
status: 'online',
user_id: currentUserId,
},
} as WebSocketMessage;
await handleStatusChangedEvent(serverUrl, msg);
expect(setCurrentUserStatus).toHaveBeenCalledWith(serverUrl, 'online');
jest.useRealTimers();
});
});
describe('handleCustomProfileAttributesValuesUpdatedEvent', () => {
it('should handle missing operator', async () => {
jest.spyOn(logUtils, 'logError').mockImplementation(() => {});
DatabaseManager.serverDatabases = {};
const msg = {
data: {
user_id: 'user1',
values: {field1: 'value1'},
},
} as WebSocketMessage;
await handleCustomProfileAttributesValuesUpdatedEvent(
serverUrl,
msg,
);
expect(logUtils.logError).toHaveBeenCalled();
});
it('should handle custom profile attributes values update', async () => {
const mockHandleCustomProfileAttributes = jest.
fn().
mockResolvedValue([]);
operator.handleCustomProfileAttributes =
mockHandleCustomProfileAttributes;
const msg = {
data: {
user_id: 'user1',
values: {
field1: 'value1',
field2: 'value2',
},
},
} as WebSocketMessage;
await handleCustomProfileAttributesValuesUpdatedEvent(
serverUrl,
msg,
);
expect(mockHandleCustomProfileAttributes).toHaveBeenCalledWith({
attributes: [
{
id: 'field1-user1',
field_id: 'field1',
user_id: 'user1',
value: 'value1',
},
{
id: 'field2-user1',
field_id: 'field2',
user_id: 'user1',
value: 'value2',
},
],
prepareRecordsOnly: false,
});
});
it('should handle errors during attributes update', async () => {
jest.spyOn(logUtils, 'logError').mockImplementation(() => {});
operator.handleCustomProfileAttributes = jest.
fn().
mockRejectedValue(new Error('test error'));
const msg = {
data: {
user_id: 'user1',
values: {field1: 'value1'},
},
} as WebSocketMessage;
await handleCustomProfileAttributesValuesUpdatedEvent(
serverUrl,
msg,
);
expect(logUtils.logError).toHaveBeenCalled();
});
it('should invalidate every cached redaction decision when the current user attributes change', async () => {
// ABAC subjects are per-user and global to the server, so one attribute write can change
// the decision for any channel. Scope, coalescing and the visible-surface refresh are
// covered in access_control.test.ts; this only asserts the handler delegates.
operator.handleCustomProfileAttributes = jest.fn().mockResolvedValue([]);
jest.mocked(getCurrentUser).mockResolvedValue(TestHelper.fakeUserModel({id: currentUserId}));
const msg = {
data: {
user_id: currentUserId,
values: {field1: 'newValue'},
},
} as WebSocketMessage;
await handleCustomProfileAttributesValuesUpdatedEvent(serverUrl, msg);
expect(invalidateRedactionForCurrentUser).toHaveBeenCalledWith(serverUrl, RedactionInvalidationReason.UserAttributes, true);
});
it('should not invalidate when a different user attributes change', async () => {
operator.handleCustomProfileAttributes = jest.fn().mockResolvedValue([]);
jest.mocked(getCurrentUser).mockResolvedValue(TestHelper.fakeUserModel({id: currentUserId}));
const msg = {
data: {
user_id: otherUserId,
values: {field1: 'newValue'},
},
} as WebSocketMessage;
await handleCustomProfileAttributesValuesUpdatedEvent(serverUrl, msg);
expect(invalidateRedactionForCurrentUser).not.toHaveBeenCalled();
});
});
describe('handleCustomProfileAttributesFieldUpdatedEvent', () => {
it('should handle missing operator', async () => {
jest.spyOn(logUtils, 'logError').mockImplementation(() => {});
DatabaseManager.serverDatabases = {};
const msg = {
data: {
field: {id: 'field1'},
},
} as WebSocketMessage;
await handleCustomProfileAttributesFieldUpdatedEvent(
serverUrl,
msg,
);
expect(logUtils.logError).toHaveBeenCalled();
});
it('should handle custom profile field update', async () => {
const mockHandleCustomProfileFields = jest.
fn().
mockResolvedValue([]);
operator.handleCustomProfileFields = mockHandleCustomProfileFields;
const mockField = {
id: 'field1',
group_id: 'group1',
name: 'Field 1',
type: 'text',
target_id: 'target1',
target_type: 'user',
create_at: 1000,
update_at: 2000,
delete_at: 0,
attrs: {required: true},
};
const msg = {
data: {
field: mockField,
},
} as WebSocketMessage;
await handleCustomProfileAttributesFieldUpdatedEvent(
serverUrl,
msg,
);
expect(mockHandleCustomProfileFields).toHaveBeenCalledWith({
fields: [mockField],
prepareRecordsOnly: false,
});
});
it('should invalidate redaction when a field is updated but not when one is created', async () => {
// Renaming an option changes what policies evaluate with no values event; a new field
// has no values yet.
operator.handleCustomProfileFields = jest.fn().mockResolvedValue([]);
const data = {field: {id: 'field1'}};
await handleCustomProfileAttributesFieldUpdatedEvent(serverUrl, {event: WebsocketEvents.CUSTOM_PROFILE_ATTRIBUTES_FIELD_CREATED, data} as WebSocketMessage);
expect(invalidateRedactionForCurrentUser).not.toHaveBeenCalled();
await handleCustomProfileAttributesFieldUpdatedEvent(serverUrl, {event: WebsocketEvents.CUSTOM_PROFILE_ATTRIBUTES_FIELD_UPDATED, data} as WebSocketMessage);
expect(invalidateRedactionForCurrentUser).toHaveBeenCalledWith(serverUrl, RedactionInvalidationReason.UserAttributes, true);
});
it('should handle errors during field update', async () => {
jest.spyOn(logUtils, 'logError').mockImplementation(() => {});
operator.handleCustomProfileFields = jest.
fn().
mockRejectedValue(new Error('test error'));
const msg = {
data: {
field: {id: 'field1'},
},
} as WebSocketMessage;
await handleCustomProfileAttributesFieldUpdatedEvent(
serverUrl,
msg,
);
expect(logUtils.logError).toHaveBeenCalled();
});
});
describe('handleCustomProfileAttributesFieldDeletedEvent', () => {
it('should handle missing operator', async () => {
jest.spyOn(logUtils, 'logError').mockImplementation(() => {});
DatabaseManager.serverDatabases = {};
const msg = {
data: {
field_id: 'field1',
},
} as WebSocketMessage;
await handleCustomProfileAttributesFieldDeletedEvent(
serverUrl,
msg,
);
expect(logUtils.logError).toHaveBeenCalled();
});
it('should handle custom profile field deletion', async () => {
// Add explicit mock setup for deleteCustomProfileAttributesByFieldId
jest.mocked(deleteCustomProfileAttributesByFieldId).mockResolvedValue();
const mockDate = 1635812400000; // Nov 1, 2021
jest.spyOn(Date, 'now').mockReturnValue(mockDate);
const msg = {
data: {
field_id: 'field1',
},
} as WebSocketMessage;
await handleCustomProfileAttributesFieldDeletedEvent(
serverUrl,
msg,
);
expect(deleteCustomProfileAttributesByFieldId).toHaveBeenCalledWith(
operator.database,
'field1',
);
});
it('should handle errors during field model deletion', async () => {
jest.spyOn(logUtils, 'logError').mockImplementation(() => {});
operator.handleCustomProfileFields = jest.fn().mockRejectedValue(new Error('test error'));
jest.mocked(deleteCustomProfileAttributesByFieldId).mockResolvedValue();
const msg = {
data: {
field_id: 'field1',
},
} as WebSocketMessage;
await handleCustomProfileAttributesFieldDeletedEvent(serverUrl, msg);
expect(logUtils.logError).toHaveBeenCalled();
expect(deleteCustomProfileAttributesByFieldId).not.toHaveBeenCalled();
});
it('should handle errors during attributes deletion', async () => {
jest.spyOn(logUtils, 'logError').mockImplementation(() => {});
jest.mocked(deleteCustomProfileAttributesByFieldId).mockRejectedValue(new Error('test error'));
const msg = {
data: {
field_id: 'field1',
},
} as WebSocketMessage;
await handleCustomProfileAttributesFieldDeletedEvent(
serverUrl,
msg,
);
expect(logUtils.logError).toHaveBeenCalled();
expect(deleteCustomProfileAttributesByFieldId).toHaveBeenCalled();
});
});
describe('handleSessionAttributesPropertyFieldEvent', () => {
const buildField = (attrs: Record<string, unknown> = {}) => JSON.stringify({
name: 'os_version',
type: 'text',
attrs: {enabled: true, platforms: ['desktop', 'mobile'], ttl_seconds: 60, grace_period_seconds: 30, ...attrs},
});
const buildMessage = (property_field?: string, objectType: string | undefined = 'session') => ({
event: 'property_field_updated',
data: {object_type: objectType, property_field},
}) as WebSocketMessage;
it('should upsert an enabled mobile field from the websocket payload', () => {
handleSessionAttributesPropertyFieldEvent(serverUrl, buildMessage(buildField()));
expect(SessionAttributesManager.upsertManifestField).toHaveBeenCalledWith(serverUrl, {
name: 'os_version',
type: 'text',
ttl_seconds: 60,
grace_period_seconds: 30,
});
expect(SessionAttributesManager.removeManifestField).not.toHaveBeenCalled();
});
it('should remove a disabled field', () => {
handleSessionAttributesPropertyFieldEvent(serverUrl, buildMessage(buildField({enabled: false})));
expect(SessionAttributesManager.removeManifestField).toHaveBeenCalledWith(serverUrl, 'os_version');
expect(SessionAttributesManager.upsertManifestField).not.toHaveBeenCalled();
});
it('should remove a field not targeted at mobile', () => {
handleSessionAttributesPropertyFieldEvent(serverUrl, buildMessage(buildField({platforms: ['desktop']})));
expect(SessionAttributesManager.removeManifestField).toHaveBeenCalledWith(serverUrl, 'os_version');
});
it('should ignore non-session object types', () => {
handleSessionAttributesPropertyFieldEvent(serverUrl, buildMessage(buildField(), 'channel'));
expect(SessionAttributesManager.upsertManifestField).not.toHaveBeenCalled();
expect(SessionAttributesManager.removeManifestField).not.toHaveBeenCalled();
});
it('should ignore events without a property field payload', () => {
handleSessionAttributesPropertyFieldEvent(serverUrl, buildMessage(undefined));
expect(SessionAttributesManager.upsertManifestField).not.toHaveBeenCalled();
expect(SessionAttributesManager.removeManifestField).not.toHaveBeenCalled();
});
});
});