Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: test cases #16860

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions packages/bot-web-ui/src/utils/__tests__/dom-observer.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { waitForDomElement } from 'Utils/dom-observer';

describe('waitForDomElement', () => {
beforeEach(() => {
document.body.innerHTML = '';
jest.clearAllMocks();
});

test('should resolve immediately if the element is already in the DOM', async () => {
rupato-deriv marked this conversation as resolved.
Show resolved Hide resolved
const elementId = 'testElement';
const div = document.createElement('div');
div.id = elementId;
document.body.appendChild(div);
const result = await waitForDomElement(`#${elementId}`);

expect(result).toBeDefined();
expect(result.id).toBe(elementId);
});

test('should resolve when the element is added to the DOM after some time', async () => {
const elementId = 'dynamicElement';

const promise = waitForDomElement(`#${elementId}`);

setTimeout(() => {
const div = document.createElement('div');
div.id = elementId;
document.body.appendChild(div);
}, 100);

const result = await promise;

expect(result).toBeDefined();
expect(result.id).toBe(elementId);
});
});
90 changes: 90 additions & 0 deletions packages/bot-web-ui/src/utils/__tests__/download.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import { LogTypes } from '@deriv/bot-skeleton';
import { localize } from '@deriv/translations';
import { getCurrentDateTimeLocale, getSuccessJournalMessage } from 'Utils/download';

jest.mock('@deriv/translations', () => ({
localize: jest.fn((message, values) => {
let result = message;
if (values) {
Object.keys(values).forEach(key => {
result = result.replace(`{{${key}}}`, values[key]);
});
}
return result;
}),
}));
Comment on lines +5 to +15
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mayuran-deriv do we need to mock @deriv/translations? There is a global mock for this in here <root>/__mocks__/translation.mock.js. Doesn't it work from there?

jest.mock('@deriv/bot-skeleton', () => ({
LogTypes: {
rupato-deriv marked this conversation as resolved.
Show resolved Hide resolved
LOAD_BLOCK: 'load_block',
PURCHASE: 'purchase',
SELL: 'sell',
NOT_OFFERED: 'not_offered',
PROFIT: 'profit',
LOST: 'lost',
WELCOME_BACK: 'welcome_back',
WELCOME: 'welcome',
},
}));
describe('getCurrentDateTimeLocale', () => {
it('should return the current date and time in UTC with the format YYYY-MM-DD HHMMSS', () => {
const result = getCurrentDateTimeLocale();
const now = new Date();
const year = now.getUTCFullYear();
const month = (now.getUTCMonth() + 1).toString().padStart(2, '0');
const day = now.getUTCDate().toString().padStart(2, '0');
const hours = now.getUTCHours().toString().padStart(2, '0');
const minutes = now.getUTCMinutes().toString().padStart(2, '0');
const seconds = now.getUTCSeconds().toString().padStart(2, '0');
const expected = `${year}-${month}-${day} ${hours}${minutes}${seconds}`;
expect(result).toBe(expected);
});
});
describe('getSuccessJournalMessage', () => {
it('should return localized message for LOAD_BLOCK', () => {
const result = getSuccessJournalMessage(LogTypes.LOAD_BLOCK, {});
expect(result).toBe('Blocks are loaded successfully');
});
it('should return localized message for PURCHASE with longcode and transaction_id', () => {
const extra = { longcode: 'Sample Longcode', transaction_id: '1234' };
const result = getSuccessJournalMessage(LogTypes.PURCHASE, extra);
expect(result).toBe('Bought: Sample Longcode (ID: 1234)');
});
it('should return localized message for SELL with sold_for', () => {
const extra = { sold_for: '100 USD' };
const result = getSuccessJournalMessage(LogTypes.SELL, extra);
expect(result).toBe('Sold for: 100 USD');
});
it('should return localized message for PROFIT with profit', () => {
const extra = { profit: '50 USD' };
const result = getSuccessJournalMessage(LogTypes.PROFIT, extra);
expect(result).toBe('Profit amount: 50 USD');
});
it('should return localized message for LOST with profit', () => {
const extra = { profit: '20 USD' };
const result = getSuccessJournalMessage(LogTypes.LOST, extra);
expect(result).toBe('Loss amount: 20 USD');
});
it('should return localized message for WELCOME_BACK with current_currency', () => {
const extra = { current_currency: 'USD' };
const result = getSuccessJournalMessage(LogTypes.WELCOME_BACK, extra);
expect(result).toBe('Welcome back! Your messages have been restored. You are using your USD account.');
});
it('should return localized message for WELCOME_BACK without current_currency', () => {
const extra = {}; // No current_currency provided
const result = getSuccessJournalMessage(LogTypes.WELCOME_BACK, extra);
expect(result).toBe('Welcome back! Your messages have been restored.');
});
it('should return localized message for WELCOME with current_currency', () => {
const extra = { current_currency: 'EUR' };
const result = getSuccessJournalMessage(LogTypes.WELCOME, extra);
expect(result).toBe('You are using your EUR account.');
});
it('should return localized message for NOT_OFFERED with empty extra', () => {
const result = getSuccessJournalMessage(LogTypes.NOT_OFFERED, {});
expect(result).toBe('Resale of this contract is not offered.');
});
it('should return empty string for unknown log type', () => {
const result = getSuccessJournalMessage('unknown_log_type' as LogTypes[keyof LogTypes], {});
expect(result).toBe('');
});
});
14 changes: 14 additions & 0 deletions packages/bot-web-ui/src/utils/__tests__/gtm.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,20 @@ describe('GTM Module', () => {
);
});

it('should directly push data layer', () => {
const mockPushDataLayer = jest.fn();
mock_store.gtm.pushDataLayer = mockPushDataLayer;

const sampleData = {
event: 'test_event',
data: { key: 'value' },
};

GTM.pushDataLayer(sampleData);

expect(mockPushDataLayer).toHaveBeenCalledWith(sampleData);
});

it('should fail on sending null for init', () => {
// eslint-disable-next-line no-console
console.warn = jest.fn();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import { addDynamicBlockToDOM } from 'Utils/xml-dom-quick-strategy';

describe('addDynamicBlockToDOM', () => {
let strategyDom: HTMLElement;

beforeEach(() => {
document.body.innerHTML = `
<div id="strategy-dom">
<value name="AMOUNT"></value>
<block type="trade_definition_tradeoptions">
<mutation></mutation>
</block>
</div>
`;
strategyDom = document.getElementById('strategy-dom')!;
});

afterEach(() => {
document.body.innerHTML = '';
});

it('should add a block to the DOM when trade_type_cat is "digits"', () => {
addDynamicBlockToDOM('testBlock', 'testValue', 'digits', strategyDom);

const valueBlock = document.querySelector('value[name="testBlock"]') as HTMLElement;
expect(valueBlock).not.toBeNull();
expect(valueBlock).toHaveAttribute('strategy_value', 'testValue');

const shadowBlock = valueBlock.querySelector('shadow') as HTMLElement;
expect(shadowBlock).not.toBeNull();
expect(shadowBlock).toHaveAttribute('type', 'math_number_positive');
expect(shadowBlock).toHaveAttribute('id', 'p0O]7-M{ZORlORxGuIEb');

const fieldBlock = shadowBlock.querySelector('field') as HTMLElement;
expect(fieldBlock).not.toBeNull();
expect(fieldBlock).toHaveAttribute('name', 'NUM');
expect(fieldBlock).toHaveTextContent('0');

const amountBlock = strategyDom.querySelector('value[name="AMOUNT"]');
const insertedBlock = amountBlock?.nextSibling as HTMLElement;
expect(insertedBlock).toBe(valueBlock);
});

it('should add a block to the DOM when trade_type_cat is "highlowticks"', () => {
addDynamicBlockToDOM('testBlockHighLow', 'testValueHighLow', 'highlowticks', strategyDom);

const valueBlock = document.querySelector('value[name="testBlockHighLow"]') as HTMLElement;
expect(valueBlock).not.toBeNull();
expect(valueBlock).toHaveAttribute('strategy_value', 'testValueHighLow');

const shadowBlock = valueBlock.querySelector('shadow') as HTMLElement;
expect(shadowBlock).not.toBeNull();
expect(shadowBlock).toHaveAttribute('type', 'math_number_positive');
expect(shadowBlock).toHaveAttribute('id', 'p0O]7-M{ZORlORxGuIEb');

const fieldBlock = shadowBlock.querySelector('field') as HTMLElement;
expect(fieldBlock).not.toBeNull();
expect(fieldBlock).toHaveAttribute('name', 'NUM');
expect(fieldBlock).toHaveTextContent('0');

const amountBlock = strategyDom.querySelector('value[name="AMOUNT"]');
const insertedBlock = amountBlock?.nextSibling as HTMLElement;
expect(insertedBlock).toBe(valueBlock);
});

it('should set has_prediction attribute when name_block is "PREDICTION"', () => {
addDynamicBlockToDOM('PREDICTION', 'testValue', '', strategyDom);

const mutationElement = strategyDom.querySelector(
'block[type="trade_definition_tradeoptions"] > mutation'
) as HTMLElement;
expect(mutationElement).not.toBeNull();
expect(mutationElement).toHaveAttribute('has_prediction', 'true');
});

it('should not modify DOM if strategy_dom is null', () => {
const initialDOM = document.body.innerHTML;
addDynamicBlockToDOM('testBlock', 'testValue', 'digits', null as unknown as HTMLElement);
expect(document.body.innerHTML).toBe(initialDOM);
});
});
2 changes: 1 addition & 1 deletion packages/bot-web-ui/src/utils/download.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export type TExtra = {
current_currency?: string;
};

const getCurrentDateTimeLocale = () => {
export const getCurrentDateTimeLocale = () => {
const date = new Date(); // This will be the current date and time

const year = date.getUTCFullYear();
Expand Down
2 changes: 1 addition & 1 deletion packages/bot-web-ui/src/utils/xml-dom-quick-strategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export const addDynamicBlockToDOM = (
shadow_block.appendChild(field_block);
block.appendChild(shadow_block);

const amount_block = strategy_dom.querySelector('value[name="AMOUNT"]');
const amount_block = strategy_dom?.querySelector('value[name="AMOUNT"]');
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mayuran-deriv is it necessary to use optional chaining here? strategy_dom is a required argument. If this one is not passed, the next lines (from lines 24 to 29) will not be covered.

if (amount_block) {
const parent_node = amount_block.parentNode;
if (parent_node) {
Expand Down
Loading