import type { Attribute } from '$conditions-core'; /** * @description Сброс атрибутов к…
- User
import type { Attribute } from '$conditions-core';
/**
-
@description Сброс атрибутов к начальным параметрам.
-
Сброс необходим при изменении условий видимости атрибута
-
*/ export const resetAttribute = (attribute: Attribute) => { const attributeType = attribute?.attributeType?.id;
const attr = { ...attribute };
switch (attributeType) { case 'SELECT': return { ...attribute, selectedOption: null, }; case 'BANK_LIST': return { ...attribute, bankList: [], }; case 'ACCOUNT_LIST': return { ...attribute, accounts: [], }; case 'PARTY_LIST': return { ...attribute, partyList: [], }; case 'PERIODS_WITH_AMOUNT_LIST': return { ...attribute, items: [], }; case 'DATE': return { ...attribute, date: null, }; case 'BOOLEAN': if (attr.childAttributes) { attr.childAttributes = []; }
return { ...attr, booleanValue: null, }; case 'NUMERIC': return { ...attribute, numeric: null, }; case 'PERCENTAGE': return { ...attribute, percent: null, }; case 'AMOUNT': return { ...attribute, amount: null, }; case 'SCALAR': return { ...attribute, scalar: null, }; default: return attribute;} }; write tests
-
- Assistant
To write tests for the
resetAttributefunction, we can utilize a testing library such as Jest. Below are some example test cases that cover various scenarios of the function according to theattributeTypeprovided.Before proceeding with the tests, ensure that you have Jest installed in your project. If not, you can install it via npm:
npm install --save-dev jestExample Test Cases for
resetAttributeHere's how the tests may look:
import { resetAttribute } from './path-to-your-file'; // Adjust the import path correctly import type { Attribute } from '$conditions-core'; describe('resetAttribute', () => { it('should reset SELECT attribute', () => { const attribute: Attribute = { attributeType: { id: 'SELECT' }, selectedOption: 'Option1' }; const result = resetAttribute(attribute); expect(result.selectedOption).toBeNull(); }); it('should reset BANK_LIST attribute', () => { const attribute: Attribute = { attributeType: { id: 'BANK_LIST' }, bankList: [{ id: '1', name: 'Bank A' }] }; const result = resetAttribute(attribute); expect(result.bankList).toEqual([]); }); it('should reset ACCOUNT_LIST attribute', () => { const attribute: Attribute = { attributeType: { id: 'ACCOUNT_LIST' }, accounts: [{ id: '1', name: 'Account A' }] }; const result = resetAttribute(attribute); expect(result.accounts).toEqual([]); }); it('should reset PARTY_LIST attribute', () => { const attribute: Attribute = { attributeType: { id: 'PARTY_LIST' }, partyList: [{ id: '1', name: 'Party A' }] }; const result = resetAttribute(attribute); expect(result.partyList).toEqual([]); }); it('should reset PERIODS_WITH_AMOUNT_LIST attribute', () => { const attribute: Attribute = { attributeType: { id: 'PERIODS_WITH_AMOUNT_LIST' }, items: [{ period: '2020-01', amount: 100 }] }; const result = resetAttribute(attribute); expect(result.items).toEqual([]); }); it('should reset DATE attribute', () => { const attribute: Attribute = { attributeType: { id: 'DATE' }, date: '2021-01-01' }; const result = resetAttribute(attribute); expect(result.date).toBeNull(); }); it('should reset BOOLEAN attribute', () => { const attribute: Attribute = { attributeType: { id: 'BOOLEAN' }, booleanValue: true, childAttributes: [{ id: 'child1' }] }; const result = resetAttribute(attribute); expect(result.booleanValue).toBeNull(); expect(result.childAttributes).toEqual([]); }); it('should reset NUMERIC attribute', () => { const attribute: Attribute = { attributeType: { id: 'NUMERIC' }, numeric: 42 }; const result = resetAttribute(attribute); expect(result.numeric).toBeNull(); }); it('should reset PERCENTAGE attribute', () => { const attribute: Attribute = { attributeType: { id: 'PERCENTAGE' }, percent: 50 }; const result = resetAttribute(attribute); expect(result.percent).toBeNull(); }); it('should reset AMOUNT attribute', () => { const attribute: Attribute = { attributeType: { id: 'AMOUNT' }, amount: 1000 }; const result = resetAttribute(attribute); expect(result.amount).toBeNull(); }); it('should reset SCALAR attribute', () => { const attribute: Attribute = { attributeType: { id: 'SCALAR' }, scalar: 'Some value' }; const result = resetAttribute(attribute); expect(result.scalar).toBeNull(); }); it('should return the original attribute for unexpected type', () => { const attribute: Attribute = { attributeType: { id: 'UNKNOWN_TYPE' }, someValue: 'Should remain the same' }; const result = resetAttribute(attribute); expect(result).toEqual(attribute); }); });Running the Tests
Make sure to add a test script in your
package.jsonto easily run the tests:"scripts": { "test": "jest" }Now you can run your tests by executing:
npm testSummary
These tests cover all possible cases indicated in the function
resetAttribute, ensuring that the function behaves as expected for various attribute types and edge cases. Adjust the import paths based on where yourresetAttributefunction is located. - User
import type { AmountAttribute, CurrencyAttribute, PeriodWithAmountListAttribute, } from '$conditions-core';
import { getXPathExpressionValue } from '../../../xml';
interface GetDefaultCurrencyFromXmlTreeProps { attributeState: AmountAttribute | CurrencyAttribute | PeriodWithAmountListAttribute; xmlTree: XMLDocument | string; propagationIndex: number; }
/**
-
Получить дефолтные валюты из Xml дерева */ export const getDefaultCurrencyFromXmlTree = (props: GetDefaultCurrencyFromXmlTreeProps) => { const { attributeState, xmlTree, propagationIndex } = props; const { defaultCurrencyValueExpr } = attributeState;
if (!defaultCurrencyValueExpr) { return attributeState; }
return { ...attributeState, defaultCurrency: getXPathExpressionValue({ expression: defaultCurrencyValueExpr, xmlTree, propagationIndex, }), }; };
-
- Assistant
To test the
getDefaultCurrencyFromXmlTreefunction effectively, we want to ensure that we cover various scenarios, including when the default currency expression is provided and when it’s not. We'll also need to mock thegetXPathExpressionValuefunction to control its output during tests.Here's a structure for writing tests for
getDefaultCurrencyFromXmlTreeusing Jest.Setting Up the Tests
First, ensure you have Jest installed as mentioned previously, and then create a test file, for example,
getDefaultCurrencyFromXmlTree.test.ts.Example Test Cases
Here’s how the tests might look:
import { getDefaultCurrencyFromXmlTree } from './path-to-your-file'; import { getXPathExpressionValue } from '../../../xml'; import type { AmountAttribute, CurrencyAttribute, PeriodWithAmountListAttribute } from '$conditions-core'; // Mock the getXPathExpressionValue function jest.mock('../../../xml', () => ({ getXPathExpressionValue: jest.fn(), })); describe('getDefaultCurrencyFromXmlTree', () => { const mockPropogationIndex = 0; // Example index const mockXmlTree = '<root><currency>USD</currency></root>'; // Example XML string afterEach(() => { jest.clearAllMocks(); // Clear mocks after each test }); it('should return the attributeState with the default currency when defaultCurrencyValueExpr is provided', () => { const mockAttributeState: AmountAttribute = { defaultCurrencyValueExpr: '/root/currency', }; // Mock the output of getXPathExpressionValue (getXPathExpressionValue as jest.Mock).mockReturnValue('USD'); const result = getDefaultCurrencyFromXmlTree({ attributeState: mockAttributeState, xmlTree: mockXmlTree, propagationIndex: mockPropogationIndex, }); expect(result).toEqual({ ...mockAttributeState, defaultCurrency: 'USD', }); expect(getXPathExpressionValue).toHaveBeenCalledWith({ expression: mockAttributeState.defaultCurrencyValueExpr, xmlTree: mockXmlTree, propagationIndex: mockPropogationIndex, }); }); it('should return the original attributeState when defaultCurrencyValueExpr is not provided', () => { const mockAttributeState: AmountAttribute = { // Note: no defaultCurrencyValueExpr }; const result = getDefaultCurrencyFromXmlTree({ attributeState: mockAttributeState, xmlTree: mockXmlTree, propagationIndex: mockPropogationIndex, }); expect(result).toEqual(mockAttributeState); expect(getXPathExpressionValue).not.toHaveBeenCalled(); // Ensure the mock function was not called }); it('should handle the case when getXPathExpressionValue returns null', () => { const mockAttributeState: CurrencyAttribute = { defaultCurrencyValueExpr: '/root/currency', }; // Mock the output to simulate it returning null (getXPathExpressionValue as jest.Mock).mockReturnValue(null); const result = getDefaultCurrencyFromXmlTree({ attributeState: mockAttributeState, xmlTree: mockXmlTree, propagationIndex: mockPropogationIndex, }); expect(result).toEqual({ ...mockAttributeState, defaultCurrency: null, }); }); it('should use the correct XMLDocument if provided instead of a string', () => { const mockAttributeState: PeriodWithAmountListAttribute = { defaultCurrencyValueExpr: '/root/currency', }; const mockXmlDoc: XMLDocument = new DOMParser().parseFromString(mockXmlTree, 'application/xml'); // Mock the output as before (getXPathExpressionValue as jest.Mock).mockReturnValue('USD'); const result = getDefaultCurrencyFromXmlTree({ attributeState: mockAttributeState, xmlTree: mockXmlDoc, propagationIndex: mockPropogationIndex, }); expect(result).toEqual({ ...mockAttributeState, defaultCurrency: 'USD', }); expect(getXPathExpressionValue).toHaveBeenCalledWith({ expression: mockAttributeState.defaultCurrencyValueExpr, xmlTree: mockXmlDoc, propagationIndex: mockPropogationIndex, }); }); });Explanation of Tests
-
Function Mocking: The
getXPathExpressionValueis mocked to control its return value during tests. -
Test Cases:
- The first test checks if the function correctly retrieves the default currency when
defaultCurrencyValueExpris provided. - The second test ensures that when
defaultCurrencyValueExprisn't present, the originalattributeStateis returned without any modifications. - The third test handles the scenario where the
getXPathExpressionValuefunction returnsnull. - The fourth test checks if the function correctly handles an
XMLDocumentinstead of an XML string.
- The first test checks if the function correctly retrieves the default currency when
Running the Tests
Add a test script in your
package.json, as shown previously, and run your tests using:npm testThis will execute all the test cases and check if your function behaves as expected. Adjust paths accordingly based on your project's structure.
-
- User
import type { Attribute, PartyListAttribute, Propagation } from '$conditions-core';
import { checkIsAccountList, checkIsAmount, checkIsBankList, checkIsBoolean, checkIsContractList, checkIsCurrency, checkIsNumeric, checkIsPartyList, checkIsPercentage, checkIsPeriodWithAmountList, checkIsRepeatingContainer, checkIsScalar, checkIsSelect, } from '../../attributeTypeGuards'; import { checkXPathExpression, injectParentIndexInAvailabilityExpression } from '../../xml'; import { createAtrAvailabilityMapper } from '../createAtrAvailabilityMapper'; import { defaultAtrValuesMapper } from '../defaultAtrValuesMapper'; import { getUpdatedBankListAttribute, getUpdatedBooleanAttribute, getUpdatedContractListAttribute, getUpdatedNumericAttribute, getUpdatedPartyListAttribute, getUpdatedPercentageAttribute, getUpdatedPeriodsWithAmountAttribute, getUpdatedRepeatContAttribute, getUpdatedScalarAttribute, getUpdatedSelectAttribute, } from './atrsUpdates'; import { getDefaultCurrencyFromXmlTree } from './getDefaultCurrencyFromXmlTree'; import { resetAttribute } from './resetAttribute';
export interface GetUpdatedAtrAvailabilityProps { attributeState: Attribute; availableAttributes: Attribute[]; propagation: Propagation; propagationIndex: number; selectedPropagationIndex: number; xmlTree: XMLDocument | string; isSavedCovenant: boolean; alwaysAvailable: boolean; isFirstRender: boolean; }
/** Устанавливаем доступность и обновляем аттрибут */ export const getUpdatedAtrAvailability = (props: GetUpdatedAtrAvailabilityProps): Attribute => { const { attributeState, propagation, propagationIndex, selectedPropagationIndex, xmlTree, alwaysAvailable, isFirstRender, } = props;
let attribute = { ...attributeState }; const { listElementIndex } = attribute; const availabilityExpr = listElementIndex == null ? attributeState.availabilityExpr : injectParentIndexInAvailabilityExpression({ expression: attributeState.availabilityExpr, parentIndex: listElementIndex, }); if (!attributeState.available && !availabilityExpr) { attribute.available = true; } // Для скрытых атрибутов нужно установить признак hidden, чтобы скрывать их на UI, но при этом хранить значение if (attributeState.visibilityExpr && xmlTree) { attribute.hidden = Boolean( !checkXPathExpression({ xmlTree, expression: attributeState.visibilityExpr, propagationIndex, }), ); } const availabilityExpressionResult = availabilityExpr && checkXPathExpression({ expression: availabilityExpr, xmlTree, propagationIndex }); if (alwaysAvailable) { attribute.available = true; return attribute; } if ( availabilityExpr && xmlTree && attributeState.available !== availabilityExpressionResult && availabilityExpressionResult !== null ) { if (availabilityExpressionResult) { const attributeWasReset = attribute?.attributeWasReset || false; const nextAttribute = attributeWasReset ? defaultAtrValuesMapper({ attribute, xmlTree, propagation, propagationIndex }) : attributeState; // eslint-disable-next-line max-depth if (attributeWasReset) { attribute.attributeWasReset = false; } const availabilityMapper = createAtrAvailabilityMapper({ xmlTree, isCompleteTree: true, propagationIndex, selectedPropagationIndex, listElementIndex, propagation, }); attribute = { ...attribute, ...(availabilityMapper(nextAttribute) || {}), }; } else { attribute.attributeWasReset = true; const nextValue = { ...resetAttribute(attributeState), available: false }; attribute = { ...nextValue, attributeWasReset: attribute.attributeWasReset, }; } } if (!attribute.available) { return attribute; } /** Сделано замыкание для упрощения использования getUpdatedAtrAvailability в прокидываемых функциях */ const getUpdatedAttributeAvailClosure = (atr: Attribute) => getUpdatedAtrAvailability({ ...props, attributeState: atr }); if (checkIsBoolean(attribute)) { attribute = getUpdatedBooleanAttribute({ ...props, attributeState: attribute, }); } if (checkIsScalar(attribute)) { attribute = getUpdatedScalarAttribute({ attributeState: attribute, xmlTree, propagationIndex }); } if (checkIsSelect(attribute)) { attribute = getUpdatedSelectAttribute({ ...props, attributeState: attribute, getUpdatedAttributeAvailClosure, }); } if (checkIsContractList(attribute)) { attribute = getUpdatedContractListAttribute({ propagation, attributeState: attribute, }); } if (checkIsAmount(attribute) || checkIsCurrency(attribute)) { attribute = getDefaultCurrencyFromXmlTree({ attributeState: attribute, xmlTree, propagationIndex, }); } if (checkIsRepeatingContainer(attribute)) { attribute = getUpdatedRepeatContAttribute({ attributeState: attribute, xmlTree, propagationIndex, }); } if (checkIsPartyList(attribute)) { attribute = getUpdatedPartyListAttribute({ ...props, attributeState: attribute, getUpdatedAttributeAvailClosure, }); } if (checkIsNumeric(attribute)) { attribute = getUpdatedNumericAttribute({ xmlTree, isSavedCovenant: props.isSavedCovenant, attributeState: attribute, isFirstRender, propagationIndex, }); } if (checkIsPercentage(attribute)) { attribute = getUpdatedPercentageAttribute({ xmlTree, isSavedCovenant: props.isSavedCovenant, attributeState: attribute, isFirstRender, propagationIndex, }); } if (checkIsPeriodWithAmountList(attribute)) { attribute = getUpdatedPeriodsWithAmountAttribute({ attributeState: attribute, xmlTree, propagationIndex, }); } if (checkIsBankList(attribute)) { attribute = getUpdatedBankListAttribute({ ...props, attributeState: attribute, getUpdatedAttributeAvailClosure, }); } if (checkIsAccountList(attribute)) { attribute = { ...attribute, accounts: attribute?.accounts || [], }; } let childAttributes: Attribute[] = []; if (attribute?.childAttributes && attribute?.childAttributes.length > 0) { childAttributes = attribute?.childAttributes.map((child, index) => { const childAttribute = { ...child }; if (checkIsPartyList(attribute)) { (childAttribute as PartyListAttribute['childAttributes'][0]).listElementIndex = index; } return getUpdatedAtrAvailability({ ...props, attributeState: childAttribute, }); }); } attribute.childAttributes = childAttributes; return attribute;};
- Assistant
Testing the
getUpdatedAtrAvailabilityfunction is essential to ensuring that it behaves correctly in various scenarios. This function takes in several props and updates the attribute's availability and state based on those props. Given the complexity of the function and its external dependencies, we need to use mocking effectively to isolate its behavior.Setting Up the Tests
To get started, ensure you have a proper test suite, possibly using Jest. Below are structured test cases to cover a variety of scenarios in the
getUpdatedAtrAvailabilityfunction.Sample Test Cases
Here’s how the tests might be structured:
import { getUpdatedAtrAvailability } from './path-to-your-file'; import { getUpdatedBankListAttribute } from './atrsUpdates'; // Mock this similarly for tests import { getDefaultCurrencyFromXmlTree } from './getDefaultCurrencyFromXmlTree'; // Mock this import { checkIsAmount } from '../../attributeTypeGuards'; // Mock this as needed import { checkXPathExpression } from '../../xml'; // Mock this as needed jest.mock('./atrsUpdates', () => ({ getUpdatedBankListAttribute: jest.fn(), getUpdatedNumericAttribute: jest.fn(), getUpdatedBooleanAttribute: jest.fn(), getUpdatedPartyListAttribute: jest.fn(), getUpdatedPercentageAttribute: jest.fn(), getUpdatedPeriodsWithAmountAttribute: jest.fn(), getUpdatedRepeatContAttribute: jest.fn(), getUpdatedSelectAttribute: jest.fn(), getUpdatedContractListAttribute: jest.fn(), getUpdatedScalarAttribute: jest.fn(), })); jest.mock('./getDefaultCurrencyFromXmlTree', () => ({ getDefaultCurrencyFromXmlTree: jest.fn(), })); jest.mock('../../xml', () => ({ checkXPathExpression: jest.fn(), })); describe('getUpdatedAtrAvailability', () => { const mockXmlTree = '<root><currency>USD</currency></root>'; // Example XML document const commonProps = { propagationIndex: 0, selectedPropagationIndex: 0, xmlTree: mockXmlTree, alwaysAvailable: false, isFirstRender: true, propagation: {} // Mock this as appropriate for your tests }; afterEach(() => { jest.clearAllMocks(); // Clear all mocks after each test }); it('should set attribute available to true if no availability expression and not already available', () => { const attributeState = { available: false, visibilityExpr: null, }; const result = getUpdatedAtrAvailability({ ...commonProps, attributeState, }); expect(result.available).toBe(true); }); it('should respect availability expression result', () => { const attributeState = { available: false, availabilityExpr: '/root/currency', }; (checkXPathExpression as jest.Mock).mockReturnValue(true); // Simulate XPath check to return true const result = getUpdatedAtrAvailability({ ...commonProps, attributeState, }); expect(result.available).toBe(true); }); it('should update boolean attributes correctly', () => { const attributeState = { available: true, attributeType: 'BOOLEAN', }; (getUpdatedBooleanAttribute as jest.Mock).mockReturnValue({ ...attributeState, updated: true }); const result = getUpdatedAtrAvailability({ ...commonProps, attributeState, }); expect(getUpdatedBooleanAttribute).toHaveBeenCalledWith({ ...commonProps, attributeState, }); expect(result.updated).toBe(true); }); it('should update amount or currency attributes correctly', () => { const attributeState = { available: true, attributeType: 'AMOUNT', }; (checkIsAmount as jest.Mock).mockReturnValue(true); (getDefaultCurrencyFromXmlTree as jest.Mock).mockReturnValue({ ...attributeState, defaultCurrency: 'USD' }); const result = getUpdatedAtrAvailability({ ...commonProps, attributeState, }); expect(getDefaultCurrencyFromXmlTree).toHaveBeenCalledWith({ attributeState, xmlTree: mockXmlTree, propagationIndex: commonProps.propagationIndex, }); expect(result.defaultCurrency).toBe('USD'); }); it('should handle child attributes', () => { const childAttrMock = { available: false, attributeType: 'BOOLEAN' }; const attributeState = { available: true, childAttributes: [childAttrMock], }; (getUpdatedBooleanAttribute as jest.Mock).mockReturnValue({ ...childAttrMock, updated: true }); const result = getUpdatedAtrAvailability({ ...commonProps, attributeState, }); const child = result.childAttributes[0]; expect(getUpdatedBooleanAttribute).toHaveBeenCalledWith({ ...commonProps, attributeState: childAttrMock, }); expect(child.updated).toBe(true); }); it('should return attribute with child attributes unchanged if no child attributes exist', () => { const attributeState = { available: true, }; const result = getUpdatedAtrAvailability({ ...commonProps, attributeState, }); expect(result.childAttributes).toEqual([]); }); it('should reset attribute correctly when availability expression fails', () => { const attributeState = { available: true, availabilityExpr: '/root/currency', }; (checkXPathExpression as jest.Mock).mockReturnValue(false); // Simulate XPath check to return false const resetAttributeMock = jest.fn().mockReturnValue({ available: false }); (resetAttribute as jest.Mock).mockImplementation(resetAttributeMock); const result = getUpdatedAtrAvailability({ ...commonProps, attributeState, }); expect(resetAttributeMock).toHaveBeenCalledWith(attributeState); expect(result.available).toBe(false); }); // Add additional tests as needed, depending on your requirements });Explanation of Tests
-
Mocking Dependencies: We mock the dependencies that are called within the
getUpdatedAtrAvailability, such asgetUpdatedBankListAttribute,checkXPathExpression, andgetDefaultCurrencyFromXmlTree. This allows us to test the function in isolation without relying on external implementations. -
Test Cases:
- The first test verifies that if there's no availability expression set and the attribute is not available, it sets the attribute’s available state to true.
- The second test checks if the function correctly respects the evaluation of an availability expression.
- The third test checks whether boolean attributes are updated correctly.
- The fourth test verifies that currency or amount attributes are updated with the appropriate default currency.
- The fifth test checks the handling of child attributes to ensure they are updated correctly.
- The sixth test asserts that an attribute with no child attributes remains unchanged.
- The seventh test ensures the attribute resets correctly when the availability expression returns false.
Running the Tests
Make sure you have a test script in your
package.json(if not already):"scripts": { "test": "jest" }Then run the tests using:
npm testThis will execute the test suite, allowing you to verify that the
getUpdatedAtrAvailabilityfunction behaves as expected across various scenarios. Adjust the import paths based on your project's structure. -
- User
import type { Attribute } from '$conditions-core';
import { checkIsAmount } from '../../../../attributeTypeGuards'; import { getXPathExpressionValue } from '../../../../xml';
type GetDefaultCurrencyProps = { attribute: Attribute; xmlTree: XMLDocument | string; propagationIndex: number; };
export const getDefaultCurrency = ({ attribute, propagationIndex, xmlTree, }: GetDefaultCurrencyProps) => { if (checkIsAmount(attribute) && attribute.defaultCurrencyValueExpr) { const nextCurrencyCode = getXPathExpressionValue({ expression: attribute.defaultCurrencyValueExpr, xmlTree, propagationIndex, });
return nextCurrencyCode || null; } return null;}; import { evaluate, XPathResult } from 'xpath';
import { XmlTreeCache } from '$conditions-core';
import { modifyXPathExpression } from '../modifyXPathExpression';
interface GetXPathExpressionValueProps { expression: string; xmlTree: XMLDocument | string; propagationIndex: number; }
/**
-
@description выполнение XPath Expression
-
@returns Значение в дереве */ export const getXPathExpressionValue = ({ expression, xmlTree, propagationIndex, }: GetXPathExpressionValueProps) => { try { // на случай, если где-то не заменено использование документа вместо строки // убрать после тестов let doc = xmlTree;
if (typeof xmlTree === 'string') { doc = XmlTreeCache.getXmlTreeFromString(xmlTree) as XMLDocument; } else { doc = xmlTree; } const modifiedExpression = modifyXPathExpression({ expression, propagationIndex }); const expressionResult = evaluate(modifiedExpression, doc, null, XPathResult.STRING_TYPE, null); return expressionResult.stringValue;} catch (err) { if (process.env.NODE_ENV !== 'production') { // eslint-disable-next-line no-console console.log('Ошибка вычисления условия', err, expression); }
return null;} };
-
- Assistant
To thoroughly test the
getDefaultCurrencyfunction provided, we will create a test suite that verifies its behavior under various conditions. This function checks if the provided attribute is of type amount and then retrieves a currency code using an XPath expression. In order to carry out the tests, we'll need to mock some dependencies, particularlycheckIsAmountandgetXPathExpressionValue.Below is an example of how to structure unit tests for the
getDefaultCurrencyfunction using Jest.Setting Up the Tests
Make sure you have Jest installed. If you haven't set up Jest, you can do so by running the following command:
npm install --save-dev jestLet's create a test file, e.g.,
getDefaultCurrency.test.ts.Example Test Cases
Here’s how the test cases might be structured:
import { getDefaultCurrency } from './path-to-your-file'; import { checkIsAmount } from '../../../../attributeTypeGuards'; import { getXPathExpressionValue } from '../../../../xml'; import type { Attribute } from '$conditions-core'; // Mock the dependencies used in getDefaultCurrency jest.mock('../../../../attributeTypeGuards', () => ({ checkIsAmount: jest.fn(), })); jest.mock('../../../../xml', () => ({ getXPathExpressionValue: jest.fn(), })); describe('getDefaultCurrency', () => { const mockPropagationIndex = 0; const mockXmlTree = '<root><currency>USD</currency></root>'; // Example XML string afterEach(() => { jest.clearAllMocks(); // Clear all mocks after each test }); it('should return the currency code when attribute is an amount and defaultCurrencyValueExpr is present', () => { const mockAttribute: Attribute = { defaultCurrencyValueExpr: '/root/currency', }; (checkIsAmount as jest.Mock).mockReturnValue(true); // Mocking that this is an amount (getXPathExpressionValue as jest.Mock).mockReturnValue('USD'); // Mocking XPath return value const result = getDefaultCurrency({ attribute: mockAttribute, xmlTree: mockXmlTree, propagationIndex: mockPropagationIndex, }); expect(checkIsAmount).toHaveBeenCalledWith(mockAttribute); expect(getXPathExpressionValue).toHaveBeenCalledWith({ expression: mockAttribute.defaultCurrencyValueExpr, xmlTree: mockXmlTree, propagationIndex: mockPropagationIndex, }); expect(result).toBe('USD'); }); it('should return null when attribute is not an amount', () => { const mockAttribute: Attribute = { defaultCurrencyValueExpr: '/root/currency', }; (checkIsAmount as jest.Mock).mockReturnValue(false); // Mocking that this is not an amount const result = getDefaultCurrency({ attribute: mockAttribute, xmlTree: mockXmlTree, propagationIndex: mockPropagationIndex, }); expect(checkIsAmount).toHaveBeenCalledWith(mockAttribute); expect(getXPathExpressionValue).not.toHaveBeenCalled(); // Should not call getXPathExpressionValue expect(result).toBeNull(); }); it('should return null when defaultCurrencyValueExpr is not present', () => { const mockAttribute: Attribute = { defaultCurrencyValueExpr: null, }; (checkIsAmount as jest.Mock).mockReturnValue(true); // Mocking that this is an amount const result = getDefaultCurrency({ attribute: mockAttribute, xmlTree: mockXmlTree, propagationIndex: mockPropagationIndex, }); expect(checkIsAmount).toHaveBeenCalledWith(mockAttribute); expect(getXPathExpressionValue).not.toHaveBeenCalled(); // Should not call getXPathExpressionValue expect(result).toBeNull(); }); it('should return null when XPath returns null', () => { const mockAttribute: Attribute = { defaultCurrencyValueExpr: '/root/currency', }; (checkIsAmount as jest.Mock).mockReturnValue(true); // Mocking that this is an amount (getXPathExpressionValue as jest.Mock).mockReturnValue(null); // Mocking XPath return value const result = getDefaultCurrency({ attribute: mockAttribute, xmlTree: mockXmlTree, propagationIndex: mockPropagationIndex, }); expect(checkIsAmount).toHaveBeenCalledWith(mockAttribute); expect(getXPathExpressionValue).toHaveBeenCalledWith({ expression: mockAttribute.defaultCurrencyValueExpr, xmlTree: mockXmlTree, propagationIndex: mockPropagationIndex, }); expect(result).toBeNull(); }); });Explanation of Tests
-
Mocking Dependencies:
- We mock
checkIsAmountto control whether the attribute is considered an amount. - We mock
getXPathExpressionValueto simulate how the function retrieves currency codes from XML.
- We mock
-
Test Cases:
- The first test checks if the function returns the correct currency code when the attribute is an amount and the expression is valid.
- The second test ensures it returns
nullwhen the attribute is not classified as an amount. - The third test ensures it returns
nullif thedefaultCurrencyValueExpris not present. - The fourth test checks that the function also returns
nullif the XPath evaluation returnsnull.
Running the Tests
To execute the tests, run the following command in your terminal:
npm testThis will run the test suite, validating the logic within the
getDefaultCurrencyfunction against various scenarios. Adjust import paths according to your project's structure. -
- User
import type { Attribute, BooleanAttribute } from '$conditions-core';
import { getXPathExpressionValue } from '../../../../../xml';
type GetDefaultBooleanValueProps = { attribute: Attribute; xmlTree: XMLDocument | string; propagationIndex: number; };
export const getDefaultBooleanValue = ({ attribute, propagationIndex, xmlTree, }: GetDefaultBooleanValueProps) => { const { defaultValueExpr, defaultValue } = attribute as BooleanAttribute;
const transformedDefaultValue = Boolean(defaultValue); if (defaultValueExpr) { const defaultValueFromExpr = getXPathExpressionValue({ expression: defaultValueExpr, xmlTree, propagationIndex, }); return typeof defaultValueFromExpr === 'string' ? (JSON.parse(defaultValueFromExpr) as boolean) : transformedDefaultValue; } return transformedDefaultValue;};
- Assistant
To properly test the
getDefaultBooleanValuefunction, you need to create unit tests that cover different scenarios. The function retrieves a default boolean value from a specified expression (defaultValueExpr) or returns a transformed default value directly from the attribute.Here's how you can set up the tests with Jest.
Setting Up the Tests
Ensure you have Jest installed, and create a new test file, for example,
getDefaultBooleanValue.test.ts.Example Test Cases
Here's how the tests might look:
import { getDefaultBooleanValue } from './path-to-your-file'; import { getXPathExpressionValue } from '../../../../../xml'; // Adjust path as needed import type { Attribute, BooleanAttribute } from '$conditions-core'; // Mock the getXPathExpressionValue function jest.mock('../../../../../xml', () => ({ getXPathExpressionValue: jest.fn(), })); describe('getDefaultBooleanValue', () => { const mockPropagationIndex = 0; const mockXmlTree = '<root><value>true</value></root>'; // Example XML string afterEach(() => { jest.clearAllMocks(); // Clear mocks after each test }); it('should return the boolean value parsed from the expression when defaultValueExpr is provided', () => { const mockAttribute: BooleanAttribute = { defaultValueExpr: '/root/value', defaultValue: 'false', // Default provided here is just an example for transformation }; (getXPathExpressionValue as jest.Mock).mockReturnValue('true'); // Simulating XPath to return a string 'true' const result = getDefaultBooleanValue({ attribute: mockAttribute, xmlTree: mockXmlTree, propagationIndex: mockPropagationIndex, }); expect(getXPathExpressionValue).toHaveBeenCalledWith({ expression: mockAttribute.defaultValueExpr, xmlTree: mockXmlTree, propagationIndex: mockPropagationIndex, }); expect(result).toBe(true); // Expecting the parsed boolean value }); it('should return the transformed default value if defaultValueExpr is not provided', () => { const mockAttribute: BooleanAttribute = { defaultValue: 'false', // Default must be a string representation of boolean defaultValueExpr: null, // No expression }; const result = getDefaultBooleanValue({ attribute: mockAttribute, xmlTree: mockXmlTree, propagationIndex: mockPropagationIndex, }); expect(getXPathExpressionValue).not.toHaveBeenCalled(); // Should not call XPath expression expect(result).toBe(false); // Expecting the transformed default value }); it('should return the transformed default value if the expression does not return a valid string', () => { const mockAttribute: BooleanAttribute = { defaultValueExpr: '/root/value', defaultValue: 'true', // again default representation for transformation }; (getXPathExpressionValue as jest.Mock).mockReturnValue(null); // Simulating XPath to return null const result = getDefaultBooleanValue({ attribute: mockAttribute, xmlTree: mockXmlTree, propagationIndex: mockPropagationIndex, }); expect(getXPathExpressionValue).toHaveBeenCalledWith({ expression: mockAttribute.defaultValueExpr, xmlTree: mockXmlTree, propagationIndex: mockPropagationIndex, }); expect(result).toBe(true); // Expecting the transformed default value from the attribute, which is true when transformed }); it('should return false if the attribute has defaultValue as a string "false"', () => { const mockAttribute: BooleanAttribute = { defaultValueExpr: null, defaultValue: 'false', // Representing boolean false }; const result = getDefaultBooleanValue({ attribute: mockAttribute, xmlTree: mockXmlTree, propagationIndex: mockPropagationIndex, }); expect(getXPathExpressionValue).not.toHaveBeenCalled(); // Should not call XPath expression expect(result).toBe(false); // Expecting false }); });Explanation of Tests
-
Mocking Dependencies:
- The
getXPathExpressionValuefunction is mocked to control its output during testing, enabling you to simulate different scenarios without needing actual XPath execution on the XML document.
- The
-
Test Cases:
- The first test asserts that when a
defaultValueExpris provided and it returns a valid string that can be parsed to a boolean, the function should return the parsed boolean value. - The second test checks that when there is no
defaultValueExpr, the function will return the transformed default value directly from the attribute. - The third test validates the scenario where the XPath expression does not return a valid value (e.g., returns
null), ensuring that the function falls back to the transformed default value. - The fourth test specifically checks the case when the default value provided as a string "false" is handled correctly.
- The first test asserts that when a
Running the Tests
To run the tests, you can execute the following command in your terminal:
npm testThis will run all the tests that you've set up, allowing you to verify that the
getDefaultBooleanValuefunction behaves as expected across various scenarios. Adjust paths according to your project's structure. -
- User
import type { Attribute, NumericAttribute, PercentageAttribute } from '$conditions-core';
import { getXPathExpressionValue } from '../../../../../xml';
type GetNumberDefaultValueProps = { attribute: Attribute; xmlTree: XMLDocument | string; propagationIndex: number; };
export const getNumberDefaultValue = ({ attribute, propagationIndex, xmlTree, }: GetNumberDefaultValueProps) => { const { defaultValueExpr, defaultValue } = attribute as NumericAttribute | PercentageAttribute;
const transformedDefaultValue = defaultValue != null ? Number(defaultValue) : null; if (defaultValueExpr) { const defaultValueFromExpr = getXPathExpressionValue({ expression: defaultValueExpr, xmlTree, propagationIndex, }); return typeof defaultValueFromExpr === 'string' ? (JSON.parse(defaultValueFromExpr) as number) : transformedDefaultValue; } return transformedDefaultValue;};
- Assistant
To effectively test the
getNumberDefaultValuefunction, we will create unit tests that cover various scenarios, including whendefaultValueExpris provided and when it is not. We will also mock dependencies likegetXPathExpressionValueto control their outputs during testing.Here's how to set up the tests.
Setting Up the Tests
Make sure you have Jest installed if not already. Create a new test file, e.g.,
getNumberDefaultValue.test.ts.Example Test Cases
Here's how the tests might look:
import { getNumberDefaultValue } from './path-to-your-file'; import { getXPathExpressionValue } from '../../../../../xml'; // Adjust the path as necessary import type { Attribute, NumericAttribute, PercentageAttribute } from '$conditions-core'; // Mock the getXPathExpressionValue function jest.mock('../../../../../xml', () => ({ getXPathExpressionValue: jest.fn(), })); describe('getNumberDefaultValue', () => { const mockPropagationIndex = 0; const mockXmlTree = '<root><value>42</value></root>'; // Example XML string afterEach(() => { jest.clearAllMocks(); // Clear mocks after each test }); it('should return the number value parsed from the expression when defaultValueExpr is provided', () => { const mockAttribute: NumericAttribute = { defaultValueExpr: '/root/value', defaultValue: '5', // Default provided here, will be transformed if expr isn't present }; (getXPathExpressionValue as jest.Mock).mockReturnValue('42'); // Simulating XPath to return a string '42' const result = getNumberDefaultValue({ attribute: mockAttribute, xmlTree: mockXmlTree, propagationIndex: mockPropagationIndex, }); expect(getXPathExpressionValue).toHaveBeenCalledWith({ expression: mockAttribute.defaultValueExpr, xmlTree: mockXmlTree, propagationIndex: mockPropagationIndex, }); expect(result).toBe(42); // Expecting the parsed number value }); it('should return the transformed default value if defaultValueExpr is not provided', () => { const mockAttribute: NumericAttribute = { defaultValue: '10', // Transforming this for test defaultValueExpr: null, // No expression }; const result = getNumberDefaultValue({ attribute: mockAttribute, xmlTree: mockXmlTree, propagationIndex: mockPropagationIndex, }); expect(getXPathExpressionValue).not.toHaveBeenCalled(); // Should not call XPath expression expect(result).toBe(10); // Expecting the transformed default value }); it('should return the transformed default value if the expression does not return a valid string', () => { const mockAttribute: PercentageAttribute = { defaultValueExpr: '/root/value', defaultValue: '20', // Default representation }; (getXPathExpressionValue as jest.Mock).mockReturnValue(null); // Simulate XPath to return null const result = getNumberDefaultValue({ attribute: mockAttribute, xmlTree: mockXmlTree, propagationIndex: mockPropagationIndex, }); expect(getXPathExpressionValue).toHaveBeenCalledWith({ expression: mockAttribute.defaultValueExpr, xmlTree: mockXmlTree, propagationIndex: mockPropagationIndex, }); expect(result).toBe(20); // Expecting the transformed default value from the attribute }); it('should return null if both defaultValueExpr and defaultValue are not provided', () => { const mockAttribute: NumericAttribute = { defaultValueExpr: null, defaultValue: null, }; const result = getNumberDefaultValue({ attribute: mockAttribute, xmlTree: mockXmlTree, propagationIndex: mockPropagationIndex, }); expect(getXPathExpressionValue).not.toHaveBeenCalled(); // Ensure no XPath call expect(result).toBeNull(); // Expecting null }); });Explanation of Tests
-
Mocking Dependencies:
- The
getXPathExpressionValuefunction is mocked to control its output during tests.
- The
-
Test Cases:
- The first test checks whether the function returns the correct number value when
defaultValueExpris provided and it evaluates to a valid string that can be parsed into a number. - The second test verifies that when there is no
defaultValueExpr, the function should return the transformed default value directly from the attribute. - The third test ensures that when the XPath returns an invalid value (like
null), the function still correctly falls back to the transformed default value. - The fourth test asserts that if neither
defaultValueExprnordefaultValueis provided, the function returnsnull.
- The first test checks whether the function returns the correct number value when
Running the Tests
To execute the tests, run the following command:
npm testThis will run the test suite you've created, allowing you to confirm that the
getNumberDefaultValuefunction behaves as expected across various scenarios. Adjust import paths based on your project's structure. -
- User
import type { Attribute, Propagation } from '$conditions-core';
import { checkXPathExpression } from '../../../../../xml';
type GetDefaultSelectedOptionProps = { attribute: Attribute; xmlTree: XMLDocument | string; propagationIndex: number; propagation: Propagation; defaultAtrValuesMapper: (props: { attribute: Attribute; xmlTree: XMLDocument | string; propagationIndex: number; propagation: Propagation; }) => Attribute; };
export const getDefaultSelectedOption = ({ attribute, propagation, propagationIndex, xmlTree, defaultAtrValuesMapper, }: GetDefaultSelectedOptionProps) => { const selectedOption = attribute.childAttributes.find( (childAtr) => childAtr.code === attribute.defaultValue || (childAtr.defaultValueExpr && checkXPathExpression({ expression: childAtr.defaultValueExpr, xmlTree, propagationIndex, })), );
if (!selectedOption) { return null; } return { ...selectedOption, childAttributes: selectedOption.childAttributes?.map((childAtr) => defaultAtrValuesMapper({ attribute: childAtr, propagation, xmlTree, propagationIndex }), ) ?? [], };};
- Assistant
To test the
getDefaultSelectedOptionfunction effectively, we will create a series of unit tests. This function retrieves a default selected option from a list of child attributes based on specific conditions. We'll need to mock thecheckXPathExpressionfunction and thedefaultAtrValuesMapperfunction to control their outputs during the tests.Here's how you can set up your tests using Jest.
Setting Up the Tests
Create a new test file, for instance,
getDefaultSelectedOption.test.ts.Example Test Cases
Here's how you can structure the tests:
import { getDefaultSelectedOption } from './path-to-your-file'; import { checkXPathExpression } from '../../../../../xml'; // Adjust path as necessary import type { Attribute, Propagation } from '$conditions-core'; // Mock the checkXPathExpression function jest.mock('../../../../../xml', () => ({ checkXPathExpression: jest.fn(), })); describe('getDefaultSelectedOption', () => { const mockXmlTree = '<root><someElement>true</someElement></root>'; // Example XML string const mockPropagationIndex = 0; // Example propagation index const mockPropagation: Propagation = {}; // Mock as necessary for additional tests afterEach(() => { jest.clearAllMocks(); // Clear mocks after each test }); it('should return selected option based on defaultValue', () => { const mockAttribute: Attribute = { defaultValue: 'option1', childAttributes: [ { code: 'option1', defaultValueExpr: null, childAttributes: [] }, { code: 'option2', defaultValueExpr: null, childAttributes: [] }, ], }; const result = getDefaultSelectedOption({ attribute: mockAttribute, xmlTree: mockXmlTree, propagationIndex: mockPropagationIndex, propagation: mockPropagation, defaultAtrValuesMapper: jest.fn(), }); expect(result).toEqual(mockAttribute.childAttributes[0]); }); it('should evaluate defaultValueExpr when code does not match', () => { const mockAttribute: Attribute = { defaultValue: 'option2', childAttributes: [ { code: 'option1', defaultValueExpr: null, childAttributes: [] }, { code: 'option2', defaultValueExpr: '/root/someElement', childAttributes: [] }, ], }; (checkXPathExpression as jest.Mock).mockReturnValue(true); // Simulate XPath returning true const result = getDefaultSelectedOption({ attribute: mockAttribute, xmlTree: mockXmlTree, propagationIndex: mockPropagationIndex, propagation: mockPropagation, defaultAtrValuesMapper: jest.fn(), }); expect(checkXPathExpression).toHaveBeenCalledWith({ expression: mockAttribute.childAttributes[1].defaultValueExpr, xmlTree: mockXmlTree, propagationIndex: mockPropagationIndex, }); expect(result).toEqual(mockAttribute.childAttributes[1]); }); it('should return null if no matching option is found', () => { const mockAttribute: Attribute = { defaultValue: 'option3', // No matching option in child attributes childAttributes: [ { code: 'option1', defaultValueExpr: null, childAttributes: [] }, { code: 'option2', defaultValueExpr: null, childAttributes: [] }, ], }; const result = getDefaultSelectedOption({ attribute: mockAttribute, xmlTree: mockXmlTree, propagationIndex: mockPropagationIndex, propagation: mockPropagation, defaultAtrValuesMapper: jest.fn(), }); expect(result).toBeNull(); }); it('should apply defaultAtrValuesMapper to child attributes of the selected option', () => { const mockAttribute: Attribute = { defaultValue: 'option1', childAttributes: [ { code: 'option1', defaultValueExpr: null, childAttributes: [{ code: 'child1' }] }, { code: 'option2', defaultValueExpr: null, childAttributes: [] }, ], }; const mockDefaultAtrValuesMapper = jest.fn((props) => ({ ...props.attribute, mapped: true })); const result = getDefaultSelectedOption({ attribute: mockAttribute, xmlTree: mockXmlTree, propagationIndex: mockPropagationIndex, propagation: mockPropagation, defaultAtrValuesMapper: mockDefaultAtrValuesMapper, }); expect(mockDefaultAtrValuesMapper).toHaveBeenCalledTimes(1); expect(result.childAttributes).toEqual([{ code: 'child1', mapped: true }]); }); });Explanation of Tests
-
Mocking Dependencies:
- The
checkXPathExpressionfunction is mocked to control its behavior, allowing us to simulate various scenarios based on XPath evaluation.
- The
-
Test Cases:
- The first test checks that the function returns an option matching the
defaultValuewhen it exists. - The second test simulates a scenario where the code does not match and checks if the expression is evaluated correctly to potentially select the option.
- The third test asserts that if no matching options are found, the function returns
null. - The fourth test verifies that the
defaultAtrValuesMapperfunction is called on the child attributes of the selected option, ensuring any mappings or transformations are applied correctly.
- The first test checks that the function returns an option matching the
Running the Tests
To run the tests, execute the following command in your terminal:
npm testThis will execute the test suite and give you feedback on whether the function behaves as expected across various test cases. Adjust import paths as necessary based on your project structure.
-
- User
import type { Attribute, Propagation } from '$conditions-core';
import { getDefaultBooleanValue } from './getDefaultBooleanValue'; import { getDefaultCurrency } from './getDefaultCurrency'; import { getDefaultSelectedOption } from './getDefaultSelectedOption'; import { getNumberDefaultValue } from './getNumberDefaultValue';
type GetDefaultValuesProps = { attribute: Attribute; xmlTree: XMLDocument | string; propagationIndex: number; propagation: Propagation; defaultAtrValuesMapper: (props: { attribute: Attribute; xmlTree: XMLDocument | string; propagationIndex: number; propagation: Propagation; }) => Attribute; };
export const getDefaultValues = ({ attribute, propagation, propagationIndex, xmlTree, defaultAtrValuesMapper, }: GetDefaultValuesProps) => { const defaultCurrency = getDefaultCurrency({ attribute, propagationIndex, xmlTree });
const defaultBooleanValue = getDefaultBooleanValue({ attribute, propagationIndex, xmlTree }); const defaultNumberValue = getNumberDefaultValue({ attribute, propagationIndex, xmlTree }); const defaultSelectedOption = getDefaultSelectedOption({ attribute, propagation, propagationIndex, xmlTree, defaultAtrValuesMapper, }); return { defaultCurrency, defaultBooleanValue, defaultNumberValue, defaultSelectedOption, };};
- Assistant
To test the
getDefaultValuesfunction, you'll need to ensure that each of its dependent functions—getDefaultCurrency,getDefaultBooleanValue,getNumberDefaultValue, andgetDefaultSelectedOption—behaves as expected when called. You will mock these dependencies in your tests to control their outputs.Here's how to set up tests for the
getDefaultValuesfunction.Setting Up the Tests
Create a new test file named
getDefaultValues.test.ts.Example Test Cases
Here's how the tests might look:
import { getDefaultValues } from './path-to-your-file'; import { getDefaultCurrency } from './getDefaultCurrency'; import { getDefaultBooleanValue } from './getDefaultBooleanValue'; import { getNumberDefaultValue } from './getNumberDefaultValue'; import { getDefaultSelectedOption } from './getDefaultSelectedOption'; import type { Attribute, Propagation } from '$conditions-core'; // Mock the dependent functions jest.mock('./getDefaultCurrency'); jest.mock('./getDefaultBooleanValue'); jest.mock('./getNumberDefaultValue'); jest.mock('./getDefaultSelectedOption'); describe('getDefaultValues', () => { const mockXmlTree = '<root><someElement>true</someElement></root>'; const mockPropagationIndex = 0; const mockPropagation: Propagation = {}; // Adjust according to your actual propagation structure afterEach(() => { jest.clearAllMocks(); // Clear mocks after each test }); it('should return all default values based on the attribute', () => { const mockAttribute: Attribute = {}; // Mock return values for each dependent function getDefaultCurrency.mockReturnValue('USD'); getDefaultBooleanValue.mockReturnValue(true); getNumberDefaultValue.mockReturnValue(42); getDefaultSelectedOption.mockReturnValue({ code: 'option1' }); const result = getDefaultValues({ attribute: mockAttribute, xmlTree: mockXmlTree, propagationIndex: mockPropagationIndex, propagation: mockPropagation, defaultAtrValuesMapper: jest.fn(), }); expect(getDefaultCurrency).toHaveBeenCalledWith({ attribute: mockAttribute, propagationIndex: mockPropagationIndex, xmlTree: mockXmlTree, }); expect(getDefaultBooleanValue).toHaveBeenCalledWith({ attribute: mockAttribute, propagationIndex: mockPropagationIndex, xmlTree: mockXmlTree, }); expect(getNumberDefaultValue).toHaveBeenCalledWith({ attribute: mockAttribute, propagationIndex: mockPropagationIndex, xmlTree: mockXmlTree, }); expect(getDefaultSelectedOption).toHaveBeenCalledWith({ attribute: mockAttribute, propagation: mockPropagation, propagationIndex: mockPropagationIndex, xmlTree: mockXmlTree, defaultAtrValuesMapper: expect.any(Function), }); expect(result).toEqual({ defaultCurrency: 'USD', defaultBooleanValue: true, defaultNumberValue: 42, defaultSelectedOption: { code: 'option1' }, }); }); it('should handle cases where getter functions return undefined', () => { const mockAttribute: Attribute = {}; // Mock return values for each dependent function getDefaultCurrency.mockReturnValue(undefined); getDefaultBooleanValue.mockReturnValue(undefined); getNumberDefaultValue.mockReturnValue(undefined); getDefaultSelectedOption.mockReturnValue(undefined); const result = getDefaultValues({ attribute: mockAttribute, xmlTree: mockXmlTree, propagationIndex: mockPropagationIndex, propagation: mockPropagation, defaultAtrValuesMapper: jest.fn(), }); expect(result).toEqual({ defaultCurrency: undefined, defaultBooleanValue: undefined, defaultNumberValue: undefined, defaultSelectedOption: undefined, }); }); });Explanation of Tests
-
Mocking Dependencies:
- Each of the functions (
getDefaultCurrency,getDefaultBooleanValue,getNumberDefaultValue, andgetDefaultSelectedOption) is mocked to control their responses during tests. This allows isolation of thegetDefaultValuesfunction behavior without depending on the implementations of these functions.
- Each of the functions (
-
Test Cases:
- The first test verifies that
getDefaultValuescorrectly calls each of the dependent functions with the appropriate arguments and returns the consolidated object with default values. - The second test checks how
getDefaultValueshandles cases where the dependent functions may returnundefined, ensuring robust handling in scenarios where values might not be available.
- The first test verifies that
Running the Tests
To execute the tests, run the following command in your terminal:
npm testThis will execute the test suite and provide feedback on the correctness of the
getDefaultValuesfunction based on the behavior defined in your tests. Adjust paths and mock implementations as necessary based on your project structure. -
- User
import type { Attribute } from '$conditions-core';
import { checkIsAmount, checkIsBoolean, checkIsNumeric, checkIsPercentage, checkIsScalar, checkIsSelect, checkIsTextList, } from '../../../../attributeTypeGuards';
type UpdateAtrByTypeProps = { updatedAttribute: Attribute; defaultBooleanValue: boolean; defaultCurrency: Nullable; defaultNumberValue: Nullable; defaultSelectedOption: Nullable; };
export const updateAtrByType = ({ defaultBooleanValue, defaultCurrency, defaultNumberValue, defaultSelectedOption, updatedAttribute, }: UpdateAtrByTypeProps) => { if (checkIsSelect(updatedAttribute)) { return { ...updatedAttribute, selectedOption: updatedAttribute.selectedOption || defaultSelectedOption, }; }
if (checkIsBoolean(updatedAttribute)) { return { ...updatedAttribute, booleanValue: updatedAttribute.booleanValue == null ? defaultBooleanValue : updatedAttribute.booleanValue, }; } if (checkIsAmount(updatedAttribute)) { return { ...updatedAttribute, currency: updatedAttribute.currency == null ? defaultCurrency : updatedAttribute.currency, }; } if (checkIsNumeric(updatedAttribute)) { return { ...updatedAttribute, numeric: updatedAttribute.numeric == null ? defaultNumberValue : Number(updatedAttribute.numeric), }; } if (checkIsPercentage(updatedAttribute)) { return { ...updatedAttribute, percent: updatedAttribute.percent == null ? defaultNumberValue : Number(updatedAttribute.percent), }; } if (checkIsTextList(updatedAttribute)) { return { ...updatedAttribute, textFields: updatedAttribute.textFields?.length > 0 ? updatedAttribute.textFields : [''], }; } if (checkIsScalar(updatedAttribute)) { return { ...updatedAttribute, scalar: typeof updatedAttribute.scalar === 'string' ? updatedAttribute.scalar : updatedAttribute.defaultValue, }; }};
- Assistant
To test the
updateAtrByTypefunction effectively, we will set up a series of unit tests that cover different attribute types. Each test will verify that the function updates the attribute based on its type and the provided default values.We will mock the attribute type guard functions (
checkIsSelect,checkIsBoolean, etc.) to simulate various scenarios. Here’s how you can set up the tests using Jest.Setting Up the Tests
Create a new test file, for example,
updateAtrByType.test.ts.Example Test Cases
Here's how the tests might be structured:
import { updateAtrByType } from './path-to-your-file'; import type { Attribute } from '$conditions-core'; // Mock the attribute type guard functions jest.mock('../../../../attributeTypeGuards', () => ({ checkIsSelect: jest.fn(), checkIsBoolean: jest.fn(), checkIsAmount: jest.fn(), checkIsNumeric: jest.fn(), checkIsPercentage: jest.fn(), checkIsScalar: jest.fn(), checkIsTextList: jest.fn(), })); describe('updateAtrByType', () => { const { checkIsSelect, checkIsBoolean, checkIsAmount, checkIsNumeric, checkIsPercentage, checkIsScalar, checkIsTextList } = require('../../../../attributeTypeGuards'); afterEach(() => { jest.clearAllMocks(); // Clear mocks after each test }); it('should update selected option for select attributes', () => { const updatedAttribute = { selectedOption: null, }; (checkIsSelect as jest.Mock).mockReturnValue(true); // Mocking as a select attribute const result = updateAtrByType({ updatedAttribute, defaultBooleanValue: false, defaultCurrency: null, defaultNumberValue: null, defaultSelectedOption: { code: 'value1' }, }); expect(result).toEqual({ ...updatedAttribute, selectedOption: { code: 'value1' }, }); }); it('should update boolean value for boolean attributes', () => { const updatedAttribute = { booleanValue: null, }; (checkIsBoolean as jest.Mock).mockReturnValue(true); // Mocking as a boolean attribute const result = updateAtrByType({ updatedAttribute, defaultBooleanValue: true, defaultCurrency: null, defaultNumberValue: null, defaultSelectedOption: null, }); expect(result).toEqual({ ...updatedAttribute, booleanValue: true, }); }); it('should update currency for amount attributes', () => { const updatedAttribute = { currency: null, }; (checkIsAmount as jest.Mock).mockReturnValue(true); // Mocking as an amount attribute const result = updateAtrByType({ updatedAttribute, defaultBooleanValue: false, defaultCurrency: 'USD', defaultNumberValue: null, defaultSelectedOption: null, }); expect(result).toEqual({ ...updatedAttribute, currency: 'USD', }); }); it('should update numeric value for numeric attributes', () => { const updatedAttribute = { numeric: null, }; (checkIsNumeric as jest.Mock).mockReturnValue(true); // Mocking as a numeric attribute const result = updateAtrByType({ updatedAttribute, defaultBooleanValue: false, defaultCurrency: null, defaultNumberValue: 10, defaultSelectedOption: null, }); expect(result).toEqual({ ...updatedAttribute, numeric: 10, }); }); it('should update percentage value for percentage attributes', () => { const updatedAttribute = { percent: null, }; (checkIsPercentage as jest.Mock).mockReturnValue(true); // Mocking as a percentage attribute const result = updateAtrByType({ updatedAttribute, defaultBooleanValue: false, defaultCurrency: null, defaultNumberValue: 25, defaultSelectedOption: null, }); expect(result).toEqual({ ...updatedAttribute, percent: 25, }); }); it('should ensure textFields are an array for text list attributes', () => { const updatedAttribute = { textFields: [], }; (checkIsTextList as jest.Mock).mockReturnValue(true); // Mocking as a text list attribute const result = updateAtrByType({ updatedAttribute, defaultBooleanValue: false, defaultCurrency: null, defaultNumberValue: null, defaultSelectedOption: null, }); expect(result).toEqual({ ...updatedAttribute, textFields: [''], }); }); it('should update scalar value for scalar attributes', () => { const updatedAttribute = { scalar: 123, defaultValue: 'defaultScalarValue', }; (checkIsScalar as jest.Mock).mockReturnValue(true); // Mocking as a scalar attribute const result = updateAtrByType({ updatedAttribute, defaultBooleanValue: false, defaultCurrency: null, defaultNumberValue: null, defaultSelectedOption: null, }); expect(result).toEqual({ ...updatedAttribute, scalar: 123, // Should remain the same as it is not undefined }); }); it('should set scalar to defaultValue if it is undefined', () => { const updatedAttribute = { scalar: undefined, defaultValue: 'defaultScalarValue', }; (checkIsScalar as jest.Mock).mockReturnValue(true); // Mocking as a scalar attribute const result = updateAtrByType({ updatedAttribute, defaultBooleanValue: false, defaultCurrency: null, defaultNumberValue: null, defaultSelectedOption: null, }); expect(result).toEqual({ ...updatedAttribute, scalar: 'defaultScalarValue', }); }); });Explanation of Tests
-
Mocking Dependencies:
Each attribute type guard function is mocked to simulate whether an attribute belongs to a specific type (e.g., select, boolean, amount, etc.). -
Test Cases:
- Each test verifies that the
updateAtrByTypefunction updates attributes correctly based on their type and respects the default values provided. - The specific conditions check whether default values are applied only when the corresponding updated value is
nullor not defined.
- Each test verifies that the
Running the Tests
To execute the tests, run:
npm testThis will run all the tests set up for the
updateAtrByTypefunction, ensuring that it behaves as expected across various scenarios. Adjust the import paths according to your project structure. -