Skip to content
TheChatArchiveThe Chat Archive
gpt-4o-mini-2024-07-18· OpenAIAi2 WildChat-4.8M (AI2)

import type { PercentageAttribute } from '$conditions-core'; import {…

  1. User

    import type { PercentageAttribute } from '$conditions-core';

    import { parseStringToNullableNumber } from '../../../../parsers'; import { getXPathExpressionValue } from '../../../../xml';

    interface GetUpdatedPercentageAttributeProps { attributeState: PercentageAttribute; xmlTree: XMLDocument; isSavedCovenant: boolean; isFirstRender: boolean; propagationIndex: number; }

    /** Обновление состояния атрибута Percentage */ export const getUpdatedPercentageAttribute = (props: GetUpdatedPercentageAttributeProps) => { const { attributeState, xmlTree, isSavedCovenant, isFirstRender, propagationIndex } = props; const { defaultValueExpr, defaultValue, percent } = attributeState;

    const defaultValueFromExpr =
    	defaultValueExpr &&
    	getXPathExpressionValue({ expression: defaultValueExpr, xmlTree, propagationIndex });
    const resolvedDefaultValue = parseStringToNullableNumber(defaultValueFromExpr) || defaultValue;
    
    const savedValue = !isSavedCovenant && isFirstRender ? resolvedDefaultValue : percent;
    
    return {
    	...attributeState,
    	percent: savedValue,
    };
    

    }; напиши тесты

  2. Assistant

    Я создам тесты для функции getUpdatedPercentageAttribute, используя библиотеку для тестирования, такую как Jest. Тесты будут проверять различные сценарии, чтобы гарантировать, что функция работает правильно во всех случаях.

    Вот пример тестов:

    import { getUpdatedPercentageAttribute } from './path/to/your/module'; // Замените путь на фактический
    import { parseStringToNullableNumber } from '../../../../parsers';
    import { getXPathExpressionValue } from '../../../../xml';
    
    jest.mock('../../../../parsers', () => ({
      parseStringToNullableNumber: jest.fn(),
    }));
    
    jest.mock('../../../../xml', () => ({
      getXPathExpressionValue: jest.fn(),
    }));
    
    describe('getUpdatedPercentageAttribute', () => {
      const mockAttributeState = {
        defaultValueExpr: 'some/xpath/expression',
        defaultValue: 50,
        percent: 75,
      };
    
      const mockXmlTree = new DOMParser().parseFromString('<root></root>', 'text/xml');
    
      beforeEach(() => {
        jest.clearAllMocks();
      });
    
      it('should return resolved default value when defaultValueExpr is provided and it returns a valid number', () => {
        (getXPathExpressionValue as jest.Mock).mockReturnValue('70');
        (parseStringToNullableNumber as jest.Mock).mockReturnValue(70);
    
        const result = getUpdatedPercentageAttribute({
          attributeState: mockAttributeState,
          xmlTree: mockXmlTree,
          isSavedCovenant: false,
          isFirstRender: true,
          propagationIndex: 0,
        });
    
        expect(result.percent).toBe(70);
      });
    
      it('should return defaultValue if defaultValueExpr cannot be resolved', () => {
        (getXPathExpressionValue as jest.Mock).mockReturnValue(null);
        (parseStringToNullableNumber as jest.Mock).mockReturnValue(null);
    
        const result = getUpdatedPercentageAttribute({
          attributeState: mockAttributeState,
          xmlTree: mockXmlTree,
          isSavedCovenant: false,
          isFirstRender: true,
          propagationIndex: 0,
        });
    
        expect(result.percent).toBe(50);
      });
    
      it('should return percent if isSavedCovenant is true and isFirstRender is false', () => {
        const result = getUpdatedPercentageAttribute({
          attributeState: mockAttributeState,
          xmlTree: mockXmlTree,
          isSavedCovenant: true,
          isFirstRender: false,
          propagationIndex: 0,
        });
    
        expect(result.percent).toBe(75);
      });
    
      it('should return defaultValue if defaultValueExpr cannot be resolved and percentage has a default', () => {
        (getXPathExpressionValue as jest.Mock).mockReturnValue(null);
        (parseStringToNullableNumber as jest.Mock).mockReturnValue(null);
    
        const result = getUpdatedPercentageAttribute({
          attributeState: mockAttributeState,
          xmlTree: mockXmlTree,
          isSavedCovenant: false,
          isFirstRender: false,
          propagationIndex: 0,
        });
    
        expect(result.percent).toBe(75);
      });
    
      it('should keep existing percent when isSavedCovenant is true', () => {
        const result = getUpdatedPercentageAttribute({
          attributeState: {
            ...mockAttributeState,
            percent: 20,
          },
          xmlTree: mockXmlTree,
          isSavedCovenant: true,
          isFirstRender: true,
          propagationIndex: 0,
        });
    
        expect(result.percent).toBe(20);
      });
    });
    

    Объяснение тестов:

    1. Тест на успешное разрешение выражения XPath: Проверяет, вернет ли функция resolvedDefaultValue корректное значение, если defaultValueExpr правильно разрешается.
    2. Тест на возврат defaultValue, если defaultValueExpr не может быть разрешено: Проверяет работу функции, когда defaultValueExpr возвращает null.
    3. Тест на возврат percent, если атрибут сохраненный, но не на первом рендере: Проверяет, что функция возвращает текущее значение percent, если это сохраненный атрибут и не первый рендер.
    4. Тест на возврат предотвращенного существующего процента: Проверяет, что функция сохраняет значение percent, если isSavedCovenant - true.
    5. Тест на случаи, когда defaultValueExpr не может быть разрешено, но percent также указан: Проверяет, что функция возвращает значение percent, когда isFirstRender - false.

    С помощью этих тестов можно убедиться в корректности работы функции getUpdatedPercentageAttribute в различных сценариях.

  3. User

    import type { PeriodWithAmountListAttribute } from '$conditions-core';

    import { getDefaultCurrencyFromXmlTree } from '../getDefaultCurrencyFromXmlTree';

    interface GetUpdatedPeriodsWithAmountAttributeProps { attributeState: PeriodWithAmountListAttribute; xmlTree: XMLDocument; propagationIndex: number; }

    /** Обновление состояния атрибута PeriodsWithAmount */ export const getUpdatedPeriodsWithAmountAttribute = ( props: GetUpdatedPeriodsWithAmountAttributeProps, ) => { const attributeWithDefaultCurrency = getDefaultCurrencyFromXmlTree( props, ) as PeriodWithAmountListAttribute; const { currency, defaultCurrency, items } = attributeWithDefaultCurrency;

    const EMPTY_PERIOD_WITH_AMOUNT = {
    	date: null,
    	currency: null,
    	amount: null,
    	year: null,
    };
    
    const newEmptyItem = { ...EMPTY_PERIOD_WITH_AMOUNT, currency: currency ?? defaultCurrency };
    
    const newItems = items && items.length ? [...items] : [newEmptyItem];
    
    return {
    	...attributeWithDefaultCurrency,
    	items: newItems,
    };
    

    };

  4. Assistant

    Для функции getUpdatedPeriodsWithAmountAttribute можно написать тесты, проверяющие различные сценарии, чтобы убедиться в ее корректной работе. Я буду использовать Jest для реализации тестов.

    Вот пример тестов для этой функции:

    import { getUpdatedPeriodsWithAmountAttribute } from './path/to/your/module'; // Укажите правильный путь до модуля
    import { getDefaultCurrencyFromXmlTree } from '../getDefaultCurrencyFromXmlTree';
    
    jest.mock('../getDefaultCurrencyFromXmlTree', () => ({
      getDefaultCurrencyFromXmlTree: jest.fn(),
    }));
    
    describe('getUpdatedPeriodsWithAmountAttribute', () => {
      const mockXmlTree = new DOMParser().parseFromString('<root></root>', 'text/xml');
    
      beforeEach(() => {
        jest.clearAllMocks();
      });
    
      it('should return items with a new empty item when items array is empty', () => {
        (getDefaultCurrencyFromXmlTree as jest.Mock).mockReturnValue({
          currency: 'USD',
          defaultCurrency: 'EUR',
          items: [],
        });
    
        const result = getUpdatedPeriodsWithAmountAttribute({
          attributeState: {},  // Предположим, здесь не требуется особое состояние
          xmlTree: mockXmlTree,
          propagationIndex: 0,
        });
    
        expect(result.items).toEqual([
          { date: null, currency: 'USD', amount: null, year: null },
        ]);
      });
    
      it('should return original items when items array is not empty', () => {
        const existingItems = [
          { date: '2022-01-01', currency: 'USD', amount: 100, year: 2022 },
          { date: '2022-02-01', currency: 'USD', amount: 200, year: 2022 },
        ];
    
        (getDefaultCurrencyFromXmlTree as jest.Mock).mockReturnValue({
          currency: null,
          defaultCurrency: 'EUR',
          items: existingItems,
        });
    
        const result = getUpdatedPeriodsWithAmountAttribute({
          attributeState: {},  // Как и раньше, здесь не требуется особое состояние
          xmlTree: mockXmlTree,
          propagationIndex: 0,
        });
    
        expect(result.items).toEqual(existingItems);
      });
    
      it('should use defaultCurrency if currency is not available', () => {
        (getDefaultCurrencyFromXmlTree as jest.Mock).mockReturnValue({
          currency: null,
          defaultCurrency: 'GBP',
          items: [],
        });
    
        const result = getUpdatedPeriodsWithAmountAttribute({
          attributeState: {}, // Без особого состояния
          xmlTree: mockXmlTree,
          propagationIndex: 0,
        });
    
        expect(result.items).toEqual([
          { date: null, currency: 'GBP', amount: null, year: null },
        ]);
      });
    
      it('should return correct structure when there are default currency and items', () => {
        const existingItems = [
          { date: '2022-01-01', currency: 'USD', amount: 100, year: 2022 },
        ];
    
        (getDefaultCurrencyFromXmlTree as jest.Mock).mockReturnValue({
          currency: 'USD',
          defaultCurrency: 'EUR',
          items: existingItems,
        });
    
        const result = getUpdatedPeriodsWithAmountAttribute({
          attributeState: {},
          xmlTree: mockXmlTree,
          propagationIndex: 0,
        });
    
        expect(result.items).toEqual(existingItems);
      });
    });
    

    Объяснение тестов:

    1. Тест на создание нового пустого элемента: Проверяет, добавляет ли функция новый пустой элемент, если массив items пуст.
    2. Тест на возврат оригинальных элементов: Проверяет, что оригинальные элементы возвращаются, если массив items не пуст.
    3. Тест на использование defaultCurrency, если currency недоступна: Проверяет, используется ли defaultCurrency, если currency отсутствует.
    4. Тест на корректную структуру, когда есть стандартная валюта и элементы: Проверяет, что при наличии существующих элементов и стандартной валюты возвращаются оригинальные элементы.

    Эти тесты охватывают основные сценарии работы функции getUpdatedPeriodsWithAmountAttribute, что позволяет удостовериться в ее корректности в различных условиях.

  5. User

    import type { ScalarAttribute } from '$conditions-core';

    import { checkIsBoolean } from '../../../../attributeTypeGuards'; import { checkXPathExpression } from '../../../../xml';

    interface GetUpdatedScalarAttributeProps { attributeState: ScalarAttribute; xmlTree: XMLDocument; propagationIndex: number; }

    /** Обновление состояния атрибута Scalar */ export const getUpdatedScalarAttribute = (props: GetUpdatedScalarAttributeProps) => { const { attributeState, xmlTree, propagationIndex } = props; const { fixReadOnlyValueExpr } = attributeState;

    let childAttributes = attributeState.childAttributes || [];
    
    const isFixed =
    	fixReadOnlyValueExpr &&
    	checkXPathExpression({ expression: fixReadOnlyValueExpr, xmlTree, propagationIndex });
    
    childAttributes = childAttributes.map((childAtr) => {
    	if (checkIsBoolean(childAtr)) {
    		return {
    			...childAtr,
    			booleanValue: false,
    		};
    	}
    
    	return childAtr;
    });
    
    return {
    	...attributeState,
    	isFixed,
    	childAttributes,
    };
    

    };

  6. Assistant

    Для функции getUpdatedScalarAttribute можно создать тесты для проверки ее поведения в различных сценариях, используя Jest для написания и выполнения этих тестов. Тесты будут проверять, правильно ли работает функция, учитывая состояния attributeState, значение fixReadOnlyValueExpr, и обработку дочерних атрибутов.

    Вот пример тестов для этой функции:

    import { getUpdatedScalarAttribute } from './path/to/your/module'; // Укажите правильный путь до модуля
    import { checkIsBoolean } from '../../../../attributeTypeGuards';
    import { checkXPathExpression } from '../../../../xml';
    
    jest.mock('../../../../attributeTypeGuards', () => ({
      checkIsBoolean: jest.fn(),
    }));
    
    jest.mock('../../../../xml', () => ({
      checkXPathExpression: jest.fn(),
    }));
    
    describe('getUpdatedScalarAttribute', () => {
      const mockXmlTree = new DOMParser().parseFromString('<root></root>', 'text/xml');
    
      const mockAttributeState = {
        fixReadOnlyValueExpr: 'valid/xpath/expression',
        childAttributes: [],
      };
    
      beforeEach(() => {
        jest.clearAllMocks();
      });
    
      it('should set isFixed to true if fixReadOnlyValueExpr is valid', () => {
        (checkXPathExpression as jest.Mock).mockReturnValue(true); // Строка XPath действительна
    
        const result = getUpdatedScalarAttribute({
          attributeState: mockAttributeState,
          xmlTree: mockXmlTree,
          propagationIndex: 0,
        });
    
        expect(result.isFixed).toBe(true);
      });
    
      it('should set isFixed to false if fixReadOnlyValueExpr is not valid', () => {
        (checkXPathExpression as jest.Mock).mockReturnValue(false); // Строка XPath недействительна
    
        const result = getUpdatedScalarAttribute({
          attributeState: mockAttributeState,
          xmlTree: mockXmlTree,
          propagationIndex: 0,
        });
    
        expect(result.isFixed).toBe(false);
      });
    
      it('should map childAttributes if childAtr is boolean', () => {
        (checkXPathExpression as jest.Mock).mockReturnValue(true);
        (checkIsBoolean as jest.Mock).mockImplementation((attr) => attr.isBoolean);
    
        const childAttributes = [{ isBoolean: true }, { isBoolean: false }];
        const attributeStateWithChilds = {
          ...mockAttributeState,
          childAttributes,
        };
    
        const result = getUpdatedScalarAttribute({
          attributeState: attributeStateWithChilds,
          xmlTree: mockXmlTree,
          propagationIndex: 0,
        });
    
        expect(result.childAttributes).toEqual([
          { isBoolean: true, booleanValue: false }, // Обновленный
          { isBoolean: false }, // Не обновленный
        ]);
      });
    
      it('should not modify childAttributes if none are boolean', () => {
        (checkXPathExpression as jest.Mock).mockReturnValue(false);
        (checkIsBoolean as jest.Mock).mockReturnValue(false);
    
        const childAttributes = [{ isBoolean: false }, { isBoolean: false }];
        const attributeStateWithChilds = {
          ...mockAttributeState,
          childAttributes,
        };
    
        const result = getUpdatedScalarAttribute({
          attributeState: attributeStateWithChilds,
          xmlTree: mockXmlTree,
          propagationIndex: 0,
        });
    
        expect(result.childAttributes).toEqual(childAttributes); // Ожидаемое отсутствие изменений
      });
    
      it('should retain existing childAttributes that are not boolean', () => {
        (checkXPathExpression as jest.Mock).mockReturnValue(true);
        (checkIsBoolean as jest.Mock).mockImplementation((attr) => attr.isBoolean);
    
        const childAttributes = [{ isBoolean: true, name: 'child1' }, { isBoolean: false, name: 'child2' }];
        const attributeStateWithChilds = {
          ...mockAttributeState,
          childAttributes,
        };
    
        const result = getUpdatedScalarAttribute({
          attributeState: attributeStateWithChilds,
          xmlTree: mockXmlTree,
          propagationIndex: 0,
        });
    
        expect(result.childAttributes).toEqual([
          { isBoolean: true, booleanValue: false, name: 'child1' },
          { isBoolean: false, name: 'child2' },
        ]);
      });
    });
    

    Объяснение тестов:

    1. Тест на установку isFixed в true: Проверяет, правильно ли устанавливается isFixed в true, когда fixReadOnlyValueExpr действителен.
    2. Тест на установку isFixed в false: Проверяет, правильно ли устанавливается isFixed в false, когда fixReadOnlyValueExpr недействителен.
    3. Тест на получение дочерних атрибутов: Проверяет, что дочерние атрибуты обновлены, когда они являются логическими (boolean), добавляя поле booleanValue.
    4. Тест на отсутствие изменений для недочерних атрибутов логического типа: Проверяет, что дочерние атрибуты остаются неизменными, если ни один из них не является логическим.
    5. Тест на сохранение существующих дочерних атрибутов, которые не являются логическими: Проверяет, что атрибуты, не являющиеся логическими, остаются неизменными и передаются в результирующий объект.

    Эти тесты обеспечивают высокую степень уверенности в том, что функция getUpdatedScalarAttribute работает правильно в различных сценариях.

  7. User

    import type { Attribute, Propagation, SelectAttribute } from '$conditions-core';

    import { checkXPathExpression } from '../../../xml';

    interface GetUpdatedBooleanAttributeProps { attributeState: SelectAttribute; availableAttributes: Attribute[]; propagation: Propagation; propagationIndex: number; selectedPropagationIndex: number; xmlTree: XMLDocument; isSavedCovenant: boolean; alwaysAvailable: boolean;

    /** Передаётся пропсом, иначе будет циклическая зависимость между функциями */
    getUpdatedAttributeAvailClosure: (atr: Attribute) => Attribute;
    

    }

    /** Обновление состояния атрибута Select */ export const getUpdatedSelectAttribute = (props: GetUpdatedBooleanAttributeProps) => { const { attributeState, xmlTree, getUpdatedAttributeAvailClosure, propagationIndex } = props;

    const fixedOption =
    	attributeState.childAttributes.find(
    		(it) =>
    			it.fixReadOnlyValueExpr &&
    			checkXPathExpression({ expression: it.fixReadOnlyValueExpr, xmlTree, propagationIndex }),
    	) || null;
    
    const defaultValueCode =
    	attributeState.defaultValue ||
    	attributeState.childAttributes.find(
    		(it) =>
    			it.available &&
    			it.defaultValueExpr &&
    			checkXPathExpression({ expression: it.defaultValueExpr, xmlTree, propagationIndex }),
    	)?.code ||
    	null;
    
    // Шаблон selectedOption для получения availabilityExpr на следующем шаге
    const selectedOptionTemplate = attributeState?.childAttributes?.find(
    	(option) => option?.code === attributeState?.selectedOption?.code,
    );
    
    // Проверяем, доступна ли выбранная опция
    const selectedOptionWithAvailability = getUpdatedAttributeAvailClosure({
    	...attributeState.selectedOption,
    	availabilityExpr: selectedOptionTemplate?.availabilityExpr ?? null,
    });
    
    const isSelectedOptionAvailable = Boolean(
    	attributeState.selectedOption && selectedOptionWithAvailability?.available,
    );
    const nextSelectedOption = isSelectedOptionAvailable
    	? attributeState.selectedOption
    	: attributeState?.childAttributes.find((it) => it.available && it.code === defaultValueCode) ||
    		({} as Partial<Attribute>);
    
    const selectedOption = attributeState.selectedOption && {
    	...nextSelectedOption,
    	childAttributes: nextSelectedOption?.childAttributes?.map((child) =>
    		getUpdatedAttributeAvailClosure(child),
    	),
    };
    
    return {
    	...attributeState,
    	fixedOption,
    	selectedOption,
    };
    

    };

  8. Assistant

    Для функции getUpdatedSelectAttribute можно написать тесты, которые будут проверять различные сценарии работы этой функции с использованием Jest. Эти тесты должны проверять корректное обновление атрибута Select на основе переданных свойств (props).

    Вот пример тестов для этой функции:

    import { getUpdatedSelectAttribute } from './path/to/your/module'; // Укажите правильный путь до модуля
    import { checkXPathExpression } from '../../../xml';
    
    jest.mock('../../../xml', () => ({
      checkXPathExpression: jest.fn(),
    }));
    
    describe('getUpdatedSelectAttribute', () => {
      const mockXmlTree = new DOMParser().parseFromString('<root></root>', 'text/xml');
    
      const mockAttributeState = {
        childAttributes: [],
        selectedOption: null,
        defaultValue: null,
      };
    
      const mockGetUpdatedAttributeAvailClosure = jest.fn((attr) => ({
        ...attr,
        available: true,  // Для теста предположим, что атрибут всегда доступен
      }));
    
      beforeEach(() => {
        jest.clearAllMocks();
      });
    
      it('should return fixedOption when a fixReadOnlyValueExpr is valid', () => {
        (checkXPathExpression as jest.Mock).mockReturnValue(true); // Шаблон XPath действителен
    
        const childAttributes = [
          {
            fixReadOnlyValueExpr: 'some/xpath/expression',
            code: 'fixedOptionCode',
          },
          {
            fixReadOnlyValueExpr: 'some/invalid/xpath/expression',
          },
        ];
        
        const attributeStateWithChilds = {
          ...mockAttributeState,
          childAttributes,
        };
    
        const result = getUpdatedSelectAttribute({
          attributeState: attributeStateWithChilds,
          xmlTree: mockXmlTree,
          propagation: {},
          propagationIndex: 0,
          selectedPropagationIndex: 0,
          availableAttributes: [],
          isSavedCovenant: false,
          alwaysAvailable: false,
          getUpdatedAttributeAvailClosure: mockGetUpdatedAttributeAvailClosure,
        });
    
        expect(result.fixedOption).toEqual(childAttributes[0]); // Проверяем, что fixedOption установлен правильно
      });
    
      it('should find defaultValueCode based on available child attributes', () => {
        (checkXPathExpression as jest.Mock).mockReturnValue(true); // Валидация XPath
    
        const childAttributes = [
          { code: 'child1', available: false, defaultValueExpr: 'valid/xpath/expression' },
          { code: 'child2', available: true, defaultValueExpr: 'valid/xpath/expression' },
        ];
        
        const attributeStateWithChilds = {
          ...mockAttributeState,
          childAttributes,
          defaultValue: null,
        };
    
        const result = getUpdatedSelectAttribute({
          attributeState: attributeStateWithChilds,
          xmlTree: mockXmlTree,
          propagation: {},
          propagationIndex: 0,
          selectedPropagationIndex: 0,
          availableAttributes: [],
          isSavedCovenant: false,
          alwaysAvailable: false,
          getUpdatedAttributeAvailClosure: mockGetUpdatedAttributeAvailClosure,
        });
    
        expect(result.selectedOption).toEqual(childAttributes[1]); // Проверяем, что selectedOption установлен на child2
      });
    
      it('should return selectedOption when available', () => {
        (checkXPathExpression as jest.Mock).mockReturnValue(true);
    
        const childAttributes = [
          { code: 'child1', available: true },
        ];
    
        const attributeStateWithChilds = {
          ...mockAttributeState,
          childAttributes,
          selectedOption: { code: 'child1' },
        };
    
        const result = getUpdatedSelectAttribute({
          attributeState: attributeStateWithChilds,
          xmlTree: mockXmlTree,
          propagation: {},
          propagationIndex: 0,
          selectedPropagationIndex: 0,
          availableAttributes: [],
          isSavedCovenant: false,
          alwaysAvailable: false,
          getUpdatedAttributeAvailClosure: mockGetUpdatedAttributeAvailClosure,
        });
    
        expect(result.selectedOption).toEqual(attributeStateWithChilds.selectedOption); // Проверяем, что возвращается выбранный вариант
      });
    
      it('should assign a fallback if selectedOption is unavailable', () => {
        (checkXPathExpression as jest.Mock).mockReturnValue(true);
    
        const childAttributes = [
          { code: 'child1', available: false },
          { code: 'child2', available: true },
        ];
    
        const attributeStateWithChilds = {
          ...mockAttributeState,
          childAttributes,
          selectedOption: { code: 'child1' }, // Выбор недоступен
          defaultValue: null,
        };
    
        const result = getUpdatedSelectAttribute({
          attributeState: attributeStateWithChilds,
          xmlTree: mockXmlTree,
          propagation: {},
          propagationIndex: 0,
          selectedPropagationIndex: 0,
          availableAttributes: [],
          isSavedCovenant: false,
          alwaysAvailable: false,
          getUpdatedAttributeAvailClosure: mockGetUpdatedAttributeAvailClosure,
        });
    
        expect(result.selectedOption).toEqual(childAttributes[1]); // Проверяем, что выбран child2 как запасной
      });
    });
    

    Объяснение тестов:

    1. Тест на установку fixedOption: Проверяет, устанавливается ли fixedOption правильно, когда fixReadOnlyValueExpr является действительным выражением XPath.
    2. Тест на поиск defaultValueCode: Убедитесь, что функция находит defaultValueCode из доступных дочерних атрибутов.
    3. Тест на возврат selectedOption, когда она доступна: Проверяет, что выбранный вариант возвращается, если он доступен в дочерних атрибутах.
    4. Тест на использование запасного варианта: Проверяет, что функция назначает запасной вариант (fallback), если выбранный вариант недоступен.

    Эти тесты эффективно проверяют различные аспекты поведения функции getUpdatedSelectAttribute, обеспечивая уверенность в том, что реализация обработки атрибутов Select работает корректно.

  9. User

    import cloneDeep from 'lodash.clonedeep';

    import type { AmountAttribute, NumericAttribute, RepeatingContainerAttribute, } from '$conditions-core';

    import { checkIsAmount, checkIsNumeric } from '../../../attributeTypeGuards'; import { getXPathExpressionNodes, getXPathExpressionValue } from '../../../xml';

    interface GetUpdatedRepeatContAttributeProps { attributeState: RepeatingContainerAttribute; xmlTree: XMLDocument; propagationIndex: number; }

    /** Обновление состояния атрибута RepeatingContainer */ export const getUpdatedRepeatContAttribute = (props: GetUpdatedRepeatContAttributeProps) => { const { attributeState, xmlTree, propagationIndex } = props; const getMembers = () => { const { pathToElements } = attributeState;

    	if (!pathToElements) {
    		return [];
    	}
    
    	const elements = getXPathExpressionNodes({
    		expression: pathToElements,
    		xmlTree,
    		propagationIndex,
    	});
    
    	if (!elements?.nodes?.length) {
    		return [];
    	}
    
    	return elements.nodes.map((it) => ({
    		id: it.getElementsByTagName('id')[0].textContent,
    		name: it.getElementsByTagName('name')[0].textContent,
    		defaultValue: it.getElementsByTagName('defaultValue')[0]?.textContent?.trim() ?? null,
    		additionalInfo: it.getElementsByTagName('additionalInfo')[0]?.textContent?.trim() ?? null,
    	}));
    };
    
    const members = getMembers();
    const childAttributes = [...attributeState?.childAttributes];
    const attributeToRepeat = cloneDeep(
    	attributeState?.repeatingElement ?? attributeState.childAttributes,
    );
    
    const isInitialAttributes = childAttributes.some(
    	(child, index) =>
    		!child?.code?.includes(members[index]?.id || '') ||
    		!child?.label?.includes(members[index]?.name || ''),
    );
    const shouldUpdateChildAttributes =
    	(isInitialAttributes && members.length) || members.length !== childAttributes.length;
    
    if (shouldUpdateChildAttributes) {
    	const newChildAttributes = members.flatMap((it, index) =>
    		attributeToRepeat.flatMap((attr) => {
    			const result = {
    				...attr,
    				code: `${attr.code}-${it?.id}`,
    				label: `${attr.label} ${it?.name}`,
    				additionalInfo: it?.additionalInfo,
    			};
    
    			if (checkIsNumeric(result) && result.numeric == null) {
    				result.numeric =
    					(childAttributes[index] as NumericAttribute)?.numeric || result.defaultValue;
    			}
    
    			if (checkIsAmount(result) && result.amount == null) {
    				result.amount =
    					(childAttributes[index] as AmountAttribute)?.amount || result.defaultValue;
    			}
    
    			if (checkIsAmount(result) && result.currency == null) {
    				const valueFromExpr = result?.defaultCurrencyValueExpr
    					? getXPathExpressionValue({
    							expression: result?.defaultCurrencyValueExpr,
    							xmlTree,
    							propagationIndex,
    						})
    					: null;
    
    				result.currency =
    					(childAttributes[index] as AmountAttribute)?.currency ||
    					it.defaultValue ||
    					valueFromExpr;
    			}
    
    			return result;
    		}),
    	);
    
    	const newAttribute = {
    		...attributeState,
    		childAttributes: newChildAttributes,
    	};
    
    	if (JSON.stringify(attributeState) !== JSON.stringify(newAttribute)) {
    		return { ...newAttribute };
    	}
    }
    
    return { ...attributeState };
    

    }; ]

  10. Assistant

    Для функции getUpdatedRepeatContAttribute, которая обновляет состояние атрибута RepeatingContainer, мы создадим тесты, чтобы проверить ее функциональность. Используя Jest, тесты будут покрывать основные случаи использования функции, включая обработку различных сценариев с дочерними атрибутами и наличием узлов, возвращаемых XPath.

    Вот пример тестов для этой функции:

    import { getUpdatedRepeatContAttribute } from './path/to/your/module'; // Укажите правильный путь до модуля
    import { checkIsAmount, checkIsNumeric } from '../../../attributeTypeGuards';
    import { getXPathExpressionNodes, getXPathExpressionValue } from '../../../xml';
    import cloneDeep from 'lodash.clonedeep';
    
    jest.mock('../../../attributeTypeGuards', () => ({
      checkIsAmount: jest.fn(),
      checkIsNumeric: jest.fn(),
    }));
    
    jest.mock('../../../xml', () => ({
      getXPathExpressionNodes: jest.fn(),
      getXPathExpressionValue: jest.fn(),
    }));
    
    describe('getUpdatedRepeatContAttribute', () => {
      const mockXmlTree = new DOMParser().parseFromString('<root></root>', 'text/xml');
    
      beforeEach(() => {
        jest.clearAllMocks();
      });
    
      it('should return empty childAttributes when pathToElements is undefined', () => {
        const attributeState = {
          pathToElements: undefined,
          childAttributes: [],
          repeatingElement: [],
        };
        
        const result = getUpdatedRepeatContAttribute({
          attributeState,
          xmlTree: mockXmlTree,
          propagationIndex: 0,
        });
    
        expect(result.childAttributes).toEqual([]); // Пустые атрибуты детей
      });
    
      it('should retrieve members based on XPath expression', () => {
        const attributeState = {
          pathToElements: 'some/xpath/expression',
          childAttributes: [],
          repeatingElement: [{ code: 'attr1', label: 'Attribute 1' }],
        };
    
        const mockNodes = [
          {
            getElementsByTagName: jest.fn().mockReturnValue([
              { textContent: '1' }, // id
              { textContent: 'Member 1' }, // name
              { textContent: 'default' }, // defaultValue
              { textContent: null }, // additionalInfo
            ]),
          },
        ];
    
        (getXPathExpressionNodes as jest.Mock).mockReturnValue({ nodes: mockNodes });
    
        const result = getUpdatedRepeatContAttribute({
          attributeState,
          xmlTree: mockXmlTree,
          propagationIndex: 0,
        });
    
        expect(result.childAttributes.length).toBe(1);
        expect(result.childAttributes[0]).toMatchObject({
          code: expect.stringContaining('attr1-1'),
          label: expect.stringContaining('Attribute 1 Member 1'),
          additionalInfo: null,
        });
      });
    
      it('should update childAttributes based on members found via XPath', () => {
        const attributeState = {
          pathToElements: 'some/xpath/expression',
          childAttributes: [{ code: 'attr1', label: 'Attr 1' }],
          repeatingElement: [{ code: 'attr1', label: 'Attribute 1' }],
        };
    
        const mockNodes = [
          {
            getElementsByTagName: jest.fn().mockReturnValue([
              { textContent: '1' }, // id
              { textContent: 'Member 1' }, // name
              { textContent: 'default' }, // defaultValue
              { textContent: null }, // additionalInfo
            ]),
          },
        ];
    
        (getXPathExpressionNodes as jest.Mock).mockReturnValue({ nodes: mockNodes });
    
        const result = getUpdatedRepeatContAttribute({
          attributeState,
          xmlTree: mockXmlTree,
          propagationIndex: 0,
        });
    
        expect(result.childAttributes.length).toBe(1);
        expect(result.childAttributes[0]).toMatchObject({
          code: 'attr1-1',
          label: 'Attribute 1 Member 1',
          additionalInfo: null,
        });
      });
    
      it('should clone repeated attributes correctly', () => {
        const attributeState = {
          pathToElements: 'some/xpath/expression',
          childAttributes: [
            { code: 'attr1', label: 'Attr 1', defaultValue: '10' },
          ],
          repeatingElement: [{ code: 'attr1', label: 'Attribute 1' }],
        };
    
        const mockNodes = [
          {
            getElementsByTagName: jest.fn().mockReturnValue([
              { textContent: '1' }, // id
              { textContent: 'Member 1' }, // name
              { textContent: 'default' }, // defaultValue
              { textContent: null }, // additionalInfo
            ]),
          },
        ];
    
        (getXPathExpressionNodes as jest.Mock).mockReturnValue({ nodes: mockNodes });
    
        (checkIsNumeric as jest.Mock).mockReturnValue(true);
        (checkIsAmount as jest.Mock).mockReturnValue(false);
        (getXPathExpressionValue as jest.Mock).mockReturnValue(null);
    
        const result = getUpdatedRepeatContAttribute({
          attributeState,
          xmlTree: mockXmlTree,
          propagationIndex: 0,
        });
    
        expect(result.childAttributes.length).toBe(1);
        expect(result.childAttributes[0]).toMatchObject({
          code: 'attr1-1',
          label: 'Attribute 1 Member 1',
          defaultValue: '10', // Значение должно наследоваться
        });
      });
    
      it('should not mutate the original attribute state if no changes are necessary', () => {
        const attributeState = {
          pathToElements: 'some/xpath/expression',
          childAttributes: [{ code: 'attr1', label: 'Attr 1' }],
          repeatingElement: [{ code: 'attr1', label: 'Attribute 1' }],
        };
    
        const mockNodes = [
          {
            getElementsByTagName: jest.fn().mockReturnValue([
              { textContent: '1' }, // id
              { textContent: 'Member 1' }, // name
              { textContent: 'default' }, // defaultValue
              { textContent: null }, // additionalInfo
            ]),
          },
        ];
    
        (getXPathExpressionNodes as jest.Mock).mockReturnValue({ nodes: mockNodes });
    
        // Ожидаем, что не будет изменений
        const originalAttributeState = cloneDeep(attributeState);
        
        const result = getUpdatedRepeatContAttribute({
          attributeState,
          xmlTree: mockXmlTree,
          propagationIndex: 0,
        });
    
        expect(originalAttributeState).toEqual(attributeState); // Проверяем, что оригинальное состояние остается неизменным
        expect(result).toEqual(attributeState); // Результат совпадает с оригиналом при отсутствии изменений
      });
    });
    

    Объяснение тестов:

    1. Тест на обработку отсутствия pathToElements: Убедитесь, что функция возвращает пустой массив для childAttributes, если pathToElements неопределен.
    2. Тест на получение членов через выражение XPath: Проверяет, возвращаются ли правильные данные, когда существует действительное выражение XPath.
    3. Тест на обновление childAttributes на основе найденных элементов: Проверяет, правильно ли обновляются childAttributes, когда новые члены извлекаются из XML.
    4. Тест на клонирование повторяющихся атрибутов: Убедитесь, что повторяющиеся атрибуты клонируются и обновляются правильно, наследуя значения из исходных атрибутов.
    5. Тест на отсутствие изменения исходного состояния: Проверяет, что если изменения не требуются, оригинальное состояние атрибута остается неизменным.

    Эти тесты обеспечивают уверенность в том, что функция getUpdatedRepeatContAttribute поведение ожидается в различных сценариях.