To write tests for the getUpdatedPropagations function, we can use a testing framework such as Jest. Below are some example tests that cover different scenarios for the getUpdatedPropagations function.
Test Setup
First, ensure that you have Jest set up in your project. Then, you can create a test file, for example, getUpdatedPropagations.test.ts. Inside this file, you can write your tests.
Sample Test File: getUpdatedPropagations.test.ts
typescript
import { getUpdatedPropagations } from './path-to-your-function'; // Adjust the import path as necessary
import { ConditionDto } from '$conditions-constructor-v2/entities/condition';
jest.mock('../../attribute', () => ({
getUpdatedAtrAvailability: jest.fn(() => ({})), // Mock as necessary
}));
describe('getUpdatedPropagations', () => {
const mockXmlTree = new DOMParser().parseFromString('<root></root>', 'text/xml');
const baseProps = {
formStateWithFormulation: {
propagations: [{ userTextAtypical: 'Test Formulation' }],
} as ConditionDto,
currentFormState: {
propagations: [{ attributes: [{}] }, { attributes: [{}] }],
} as ConditionDto,
xmlTree: mockXmlTree,
selectedPropagationIndex: 0,
isSavedCovenant: false,
passAll: false,
alwaysAvailable: false,
isFirstRender: false,
};
it('should return updated propagations for the selected index', () => {
const result = getUpdatedPropagations({ ...baseProps, selectedPropagationIndex: 0 });
expect(result).toHaveLength(2);
expect(result[0]).toEqual(expect.objectContaining({
userTextAtypical: 'Test Formulation',
attributes: expect.any(Array),
}));
expect(result[1]).toEqual(expect.objectContaining({
userTextAtypical: null,
attributes: undefined,
}));
});
it('should return updated propagations for all when passAll is true', () => {
const result = getUpdatedPropagations({ ...baseProps, passAll: true });
expect(result).toHaveLength(2);
result.forEach((propagation, index) => {
expect(propagation).toEqual(expect.objectContaining({
userTextAtypical: 'Test Formulation',
attributes: expect.any(Array),
}));
});
});
it('should not update other propagations if not selected', () => {
const result = getUpdatedPropagations({ ...baseProps, selectedPropagationIndex: 1 });
expect(result).toHaveLength(2);
expect(result[1]).toEqual(expect.objectContaining({
userTextAtypical: null,
attributes: expect.any(Array),
}));
expect(result[0]).toEqual(expect.objectContaining({
userTextAtypical: null,
attributes: undefined,
}));
});
it('should handle the first render case with alwaysAvailable', () => {
const result = getUpdatedPropagations({ ...baseProps, alwaysAvailable: true, isFirstRender: true });
// Add specific assertions based on your logic for this case
expect(result).toBeDefined();
});
});
Explanation of the Tests
Test for updating at a specific index: This test checks that when you select a specific propagation (index 0), it updates its attributes and formulation, while the one not selected remains unchanged.
Test for passAll feature: This scenario tests that when passAll is true, all propagations are updated regardless of the selected index.
Test for non-selected propagation: By selecting propagation index 1, we verify that only the appropriate propagation is updated and the rest remain in their initial states.
First render and always available: This test checks the behavior when both isFirstRender and alwaysAvailable flags are set to true, although specific assertions would depend on your functional requirements.
Important Notes
Make sure to adjust the import paths according to your file structure.
The implementation of getUpdatedAtrAvailability is mocked here, as its behavior isn't provided. You can provide a more detailed mock based on your actual implementation.
You can enhance the tests by adding more edge cases based on your functional requirements.
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 {
getUpdatedBankListAttribute,
getUpdatedBooleanAttribute,
getUpdatedContractListAttribute,
getUpdatedNumericAttribute,
getUpdatedPartyListAttribute,
getUpdatedPercentageAttribute,
getUpdatedPeriodsWithAmountAttribute,
getUpdatedRepeatContAttribute,
getUpdatedScalarAttribute,
getUpdatedSelectAttribute,
} from './atrsUpdates';
import { createAtrAvailabilityMapper } from './createAtrAvailabilityMapper';
import { defaultAtrValuesMapper } from './defaultAtrValuesMapper';
import { getDefaultCurrencyFromXmlTree } from './getDefaultCurrencyFromXmlTree';
import { resetAttribute } from './resetAttribute';
To create tests for the getUpdatedAtrAvailability function, we can again utilize Jest as our testing framework. The tests will verify various scenarios, making sure that the function behaves correctly for different attributes, visibility conditions, and XML configurations.
Sample Test File: getUpdatedAtrAvailability.test.ts
First, ensure you have the necessary setup in your project with Jest. Then create a test file named getUpdatedAtrAvailability.test.ts with the following content:
typescript
import { getUpdatedAtrAvailability, GetUpdatedAtrAvailabilityProps } from './path-to-your-function'; // Adjust the import path
import type { Attribute, Propagation } from '$conditions-core';
import { DOMParser } from 'xmldom'; // Assuming XML parsing comes from xmldom
jest.mock('../../attributeTypeGuards', () => ({
checkIsBoolean: jest.fn().mockReturnValue(false),
checkIsScalar: jest.fn().mockReturnValue(false),
checkIsSelect: jest.fn().mockReturnValue(false),
checkIsContractList: jest.fn().mockReturnValue(false),
checkIsAmount: jest.fn().mockReturnValue(false),
checkIsCurrency: jest.fn().mockReturnValue(false),
checkIsRepeatingContainer: jest.fn().mockReturnValue(false),
checkIsPartyList: jest.fn().mockReturnValue(false),
checkIsNumeric: jest.fn().mockReturnValue(false),
checkIsPercentage: jest.fn().mockReturnValue(false),
checkIsPeriodWithAmountList: jest.fn().mockReturnValue(false),
checkIsBankList: jest.fn().mockReturnValue(false),
checkIsAccountList: jest.fn().mockReturnValue(false),
}));
jest.mock('./atrsUpdates', () => ({
getUpdatedBooleanAttribute: jest.fn().mockImplementation((props) => ({ ...props.attributeState, updated: true })),
getUpdatedScalarAttribute: jest.fn().mockImplementation((props) => ({ ...props.attributeState, updated: true })),
getUpdatedSelectAttribute: jest.fn().mockImplementation((props) => ({ ...props.attributeState, updated: true })),
// Add mocks for other attribute update functions as necessary
}));
// Mock functions for XML operations
jest.mock('../../xml', () => ({
checkXPathExpression: jest.fn(() => true),
injectParentIndexInAvailabilityExpression: jest.fn(expression => expression),
}));
describe('getUpdatedAtrAvailability', () => {
const xmlTree = new DOMParser().parseFromString('<root></root>', 'text/xml');
it('should initialize attribute properties properly', () => {
const attributeState = {
available: false,
visibilityExpr: '',
availabilityExpr: '',
childAttributes: [],
attributeWasReset: false,
} as Attribute;
const propagation = {} as Propagation;
const props: GetUpdatedAtrAvailabilityProps = {
attributeState,
propagation,
propagationIndex: 0,
selectedPropagationIndex: 0,
xmlTree,
isSavedCovenant: false,
alwaysAvailable: false,
isFirstRender: true,
};
const updatedAttribute = getUpdatedAtrAvailability(props);
expect(updatedAttribute).toEqual(expect.objectContaining({
available: true, // Initially should be available
hidden: false, // Based on visibility conditions
}));
});
it('should set attribute as hidden if visibility expression is false', () => {
const attributeState = {
available: true,
visibilityExpr: 'some-expression',
availabilityExpr: null,
childAttributes: [],
} as Attribute;
const propagation = {} as Propagation;
// Mocking checkXPathExpression return value to simulate hidden attributes
const checkXPathExpression = require('../../xml').checkXPathExpression;
checkXPathExpression.mockReturnValue(false); // Simulate visibility check
const props: GetUpdatedAtrAvailabilityProps = {
attributeState,
propagation,
propagationIndex: 0,
selectedPropagationIndex: 0,
xmlTree,
isSavedCovenant: false,
alwaysAvailable: false,
isFirstRender: true,
};
const updatedAttribute = getUpdatedAtrAvailability(props);
expect(updatedAttribute.hidden).toBe(true);
});
it('should return available attribute updated by specific type check', () => {
const attributeState = {
available: true,
visibilityExpr: null,
availabilityExpr: null,
childAttributes: [],
} as Attribute;
// Mock to indicate that the attribute is a boolean
const checkIsBoolean = require('../../attributeTypeGuards').checkIsBoolean;
checkIsBoolean.mockReturnValue(true);
const propagation = {} as Propagation;
const props: GetUpdatedAtrAvailabilityProps = {
attributeState,
propagation,
propagationIndex: 0,
selectedPropagationIndex: 0,
xmlTree,
isSavedCovenant: false,
alwaysAvailable: false,
isFirstRender: true,
};
const updatedAttribute = getUpdatedAtrAvailability(props);
expect(updatedAttribute).toHaveProperty('updated', true); // Expect boolean update function to have some updated property
});
// Additional tests for various scenarios can be added here
});
Explanation of the Tests
Initialization Test: This test initializes an Attribute and checks that the getUpdatedAtrAvailability function sets the correct properties, particularly ensuring that the attribute is available initially as per the function logic.
Visibility Expression Test: This test checks that when the visibility expression evaluates to false (indicating that the attribute should be hidden), the function marks the attribute as hidden.
Type-Specific Update Test: This test mocks the type check function for boolean attributes to verify that the correct attribute update function is called (in this case, the boolean updater), and checks for an expected property in the updated attribute.
Important Notes
Make sure to adjust the paths to the mocks and imports based on your project structure.
You may need to add additional logic or mock functions based on how your specific application handles certain attributes.
Consider adding more tests to cover edge cases and variations in behavior, particularly around other types of attributes, conditions for saving covenants, or the effects of first render states.
To ensure comprehensive coverage for the getUpdatedAtrAvailability function, we'll write additional unit tests that address each key pathway and case within the function's logic. These tests will focus on different types of attributes, various state conditions, visibility expressions, and the effects of the XML tree.
Here’s a more exhaustive set of test cases for your provided function, ensuring we capture as many scenarios as possible:
Complete Test File: getUpdatedAtrAvailability.test.ts
typescript
import { getUpdatedAtrAvailability, GetUpdatedAtrAvailabilityProps } from './path-to-your-function';
import type { Attribute, Propagation } from '$conditions-core';
import { DOMParser } from 'xmldom'; // Update if using a different XML library
jest.mock('../../attributeTypeGuards', () => ({
checkIsBoolean: jest.fn(),
checkIsScalar: jest.fn(),
checkIsSelect: jest.fn(),
checkIsContractList: jest.fn(),
checkIsAmount: jest.fn(),
checkIsCurrency: jest.fn(),
checkIsRepeatingContainer: jest.fn(),
checkIsPartyList: jest.fn(),
checkIsNumeric: jest.fn(),
checkIsPercentage: jest.fn(),
checkIsPeriodWithAmountList: jest.fn(),
checkIsBankList: jest.fn(),
checkIsAccountList: jest.fn(),
}));
jest.mock('./atrsUpdates', () => ({
getUpdatedBooleanAttribute: jest.fn().mockImplementation((props) => ({ ...props.attributeState, updated: true })),
getUpdatedScalarAttribute: jest.fn().mockImplementation((props) => ({ ...props.attributeState, updated: true })),
getUpdatedSelectAttribute: jest.fn().mockImplementation((props) => ({ ...props.attributeState, updated: true })),
getUpdatedContractListAttribute: jest.fn().mockImplementation((props) => ({ ...props.attributeState, updated: true })),
getUpdatedNumericAttribute: jest.fn().mockImplementation((props) => ({ ...props.attributeState, updated: true })),
getUpdatedPercentageAttribute: jest.fn().mockImplementation((props) => ({ ...props.attributeState, updated: true })),
getUpdatedPeriodsWithAmountAttribute: jest.fn().mockImplementation((props) => ({ ...props.attributeState, updated: true })),
getUpdatedRepeatContAttribute: jest.fn().mockImplementation((props) => ({ ...props.attributeState, updated: true })),
getUpdatedPartyListAttribute: jest.fn().mockImplementation((props) => ({ ...props.attributeState, updated: true })),
getUpdatedBankListAttribute: jest.fn().mockImplementation((props) => ({ ...props.attributeState, updated: true })),
}));
jest.mock('../../xml', () => ({
checkXPathExpression: jest.fn(() => true),
injectParentIndexInAvailabilityExpression: jest.fn(expression => expression),
}));
describe('getUpdatedAtrAvailability', () => {
const xmlTree = new DOMParser().parseFromString('<root></root>', 'text/xml');
afterEach(() => {
jest.clearAllMocks();
});
it('should initialize attribute properties properly', () => {
const attributeState = {
available: false,
visibilityExpr: '',
availabilityExpr: '',
childAttributes: [],
} as Attribute;
const propagation = {} as Propagation;
const props: GetUpdatedAtrAvailabilityProps = {
attributeState,
propagation,
propagationIndex: 0,
selectedPropagationIndex: 0,
xmlTree,
isSavedCovenant: false,
alwaysAvailable: false,
isFirstRender: true,
};
const updatedAttribute = getUpdatedAtrAvailability(props);
expect(updatedAttribute).toEqual(expect.objectContaining({
available: true,
hidden: false,
}));
});
it('should set attribute as hidden if visibility expression evaluates to false', () => {
const attributeState = {
available: true,
visibilityExpr: 'some-expression',
availabilityExpr: null,
childAttributes: [],
} as Attribute;
const propagation = {} as Propagation;
const checkXPathExpression = require('../../xml').checkXPathExpression;
checkXPathExpression.mockReturnValue(false); // Simulate visibility check
const props: GetUpdatedAtrAvailabilityProps = {
attributeState,
propagation,
propagationIndex: 0,
selectedPropagationIndex: 0,
xmlTree,
isSavedCovenant: false,
alwaysAvailable: false,
isFirstRender: true,
};
const updatedAttribute = getUpdatedAtrAvailability(props);
expect(updatedAttribute.hidden).toBe(true);
});
it('should make attribute always available if alwaysAvailable is true', () => {
const attributeState = {
available: false,
visibilityExpr: null,
availabilityExpr: null,
childAttributes: [],
} as Attribute;
const propagation = {} as Propagation;
const props: GetUpdatedAtrAvailabilityProps = {
attributeState,
propagation,
propagationIndex: 0,
selectedPropagationIndex: 0,
xmlTree,
isSavedCovenant: false,
alwaysAvailable: true,
isFirstRender: true,
};
const updatedAttribute = getUpdatedAtrAvailability(props);
expect(updatedAttribute.available).toBe(true);
});
it('should reset attribute and set available to false if availability expression evaluates to false', () => {
const attributeState = {
available: true,
visibilityExpr: null,
availabilityExpr: 'some-expression',
childAttributes: [],
attributeWasReset: false,
} as Attribute;
const propagation = {} as Propagation;
const checkXPathExpression = require('../../xml').checkXPathExpression;
checkXPathExpression.mockReturnValue(false); // Simulate availability check
const props: GetUpdatedAtrAvailabilityProps = {
attributeState,
propagation,
propagationIndex: 0,
selectedPropagationIndex: 0,
xmlTree,
isSavedCovenant: false,
alwaysAvailable: false,
isFirstRender: true,
};
const updatedAttribute = getUpdatedAtrAvailability(props);
expect(updatedAttribute.available).toBe(false);
expect(updatedAttribute.attributeWasReset).toBe(true);
});
it('should call correct update functions for specific attribute types', () => {
const attributeState = {
available: true,
visibilityExpr: null,
availabilityExpr: null,
childAttributes: [],
} as Attribute;
const propagation = {} as Propagation;
const props: GetUpdatedAtrAvailabilityProps = {
attributeState,
propagation,
propagationIndex: 0,
selectedPropagationIndex: 0,
xmlTree,
isSavedCovenant: false,
alwaysAvailable: false,
isFirstRender: true,
};
// Test for boolean
require('../../attributeTypeGuards').checkIsBoolean.mockReturnValue(true);
const updatedAttribute = getUpdatedAtrAvailability(props);
expect(updatedAttribute.updated).toBe(true); // Expecting boolean update function to set updated
// Test for scalar after resetting mock
jest.clearAllMocks();
require('../../attributeTypeGuards').checkIsBoolean.mockReturnValue(false);
require('../../attributeTypeGuards').checkIsScalar.mockReturnValue(true);
const updatedScalarAttribute = getUpdatedAtrAvailability(props);
expect(updatedScalarAttribute.updated).toBe(true); // Expecting scalar update function to set updated
// Extend similarly for other types as needed
});
it('should handle child attributes correctly', () => {
const attributeState = {
available: true,
visibilityExpr: null,
availabilityExpr: null,
childAttributes: [{}, {}], // Simulating two child attributes
} as Attribute;
const propagation = {} as Propagation;
const props: GetUpdatedAtrAvailabilityProps = {
attributeState,
propagation,
propagationIndex: 0,
selectedPropagationIndex: 0,
xmlTree,
isSavedCovenant: false,
alwaysAvailable: false,
isFirstRender: true,
};
const updatedAttribute = getUpdatedAtrAvailability(props);
expect(updatedAttribute.childAttributes).toHaveLength(2);
updatedAttribute.childAttributes.forEach((childAttr) => {
expect(childAttr).toBeDefined(); // Modify as per expected values from child attributes logic
});
});
it('should correctly handle when attribute is a currency or amount', () => {
const attributeState = {
available: true,
visibilityExpr: null,
availabilityExpr: null,
childAttributes: [],
type: 'currency' // or 'amount'
} as Attribute;
const propagation = {} as Propagation;
require('../../attributeTypeGuards').checkIsAmount.mockReturnValue(true);
const props: GetUpdatedAtrAvailabilityProps = {
attributeState,
propagation,
propagationIndex: 0,
selectedPropagationIndex: 0,
xmlTree,
isSavedCovenant: false,
alwaysAvailable: false,
isFirstRender: true,
};
const updatedAttribute = getUpdatedAtrAvailability(props);
expect(updatedAttribute).toHaveProperty('currency', expect.anything()); // Assuming gets currency from XML
});
it('should only return available attributes if other conditions are not met', () => {
const attributeState = {
available: true,
visibilityExpr: null,
availabilityExpr: null,
childAttributes: [],
} as Attribute;
const propagation = {} as Propagation;
const props: GetUpdatedAtrAvailabilityProps = {
attributeState,
propagation,
propagationIndex: 0,
selectedPropagationIndex: 0,
xmlTree,
isSavedCovenant: false,
alwaysAvailable: false,
isFirstRender: false,
};
const updatedAttribute = getUpdatedAtrAvailability(props);
expect(updatedAttribute.available).toBe(true); // Attribute remains available
});
// Add additional test cases for specific scenarios, injecting mock conditions as necessary
});
Key Test Inclusions
Initialization: Tests that the initial attribute properties are set correctly.
Visibility Expressions: Checks whether attributes are hidden based on the visibility expression.
Always Available Logic: Ensures attributes remain available when alwaysAvailable is set to true.
Reset Logic: Tests that the attribute resets when the availability expression evaluates to false.
Type-Specific Updates: Verifies that the correct attribute update functions are called for boolean and scalar types, and mocks for other types can be extended similarly.
Child Attributes Handling: Confirms that child attributes are processed correctly and returns expected results.
Handling Amount/Currency Attributes: Specifically tests the handling logic for currency and amount attributes.
Available Attribute Checks: Verifies that only attributes which meet the availability conditions are returned.
Next Steps
After writing these tests, run them using your test runner (e.g., Jest) to ensure they pass and correctly cover the expected behaviors of the getUpdatedAtrAvailability function.
You may want to add even more specific tests depending on the implementation details and how conditions affect the attributes, to ensure full coverage.
Continuously refactor the tests as the application grows, keeping them up to date with changes in logic or functionality.