*/ export const getXPathExpressionNodes = ({ expression, xmlTree, propagationIndex, }:…
- User
*/ export const getXPathExpressionNodes = ({ expression, xmlTree, propagationIndex, }: GetXPathExpressionNodesProps) => { try { const modifiedExpression = modifyXPathExpression({ expression, propagationIndex });
return evaluate(modifiedExpression, xmlTree, null, XPathResult.ANY_TYPE, null); } catch (err) { if (process.env.NODE_ENV !== 'production') { // eslint-disable-next-line no-console console.log('Ошибка вычисления условия', err, expression); } return null; }}; test('should return null when an error occurs', () => { const consoleSpy = jest.spyOn(console, 'log').mockImplementation(() => {});
const xmlString = '<data></data>'; const mockXMLDocument = new DOMParser().parseFromString(xmlString, 'application/xml'); (modifyXPathExpression as jest.Mock).mockReturnValueOnce(new Error('Error')); const result = getXPathExpressionNodes({ expression: '//group', xmlTree: mockXMLDocument, }); expect(result).toBeNull(); expect(consoleSpy).toHaveBeenCalledWith( 'Ошибка вычисления условия', expect.any(Error), '//group', ); });√ should evaluate the expression on an XMLDocument without converting (2 ms)● getXPathExpressionNodes › should return null when an error occurs
expect(received).toBeNull() Received: {"iterateNext": [Function mockConstructor]} 78 | }); 79 | > 80 | expect(result).toBeNull(); | ^ 81 | expect(consoleSpy).toHaveBeenCalledWith( 82 | 'Ошибка вычисления условия', 83 | expect.any(Error), - Assistant
The test you've written is intended to check that the function
getXPathExpressionNodesreturnsnullwhen an error occurs, specifically when an issue arises in themodifyXPathExpressionfunction. However, based on the error message you provided, it seems that the return value fromgetXPathExpressionNodesis notnull, but an object representing an XPath result.Here are possible reasons for this issue and suggestions on how to fix it:
Possible Issues
-
Error Handling in
modifyXPathExpression: ThemodifyXPathExpressionis supposed to throw an error or return a specific value for the test to execute correctly. If it simply returns an error object rather than throwing it, thecatchblock ingetXPathExpressionNodeswon't execute correctly. -
Mock Implementation: The current mock of
modifyXPathExpressionmight not correctly simulate the error scenario you intended. -
Xpath Evaluation Fallback: If
evaluateis called aftermodifyXPathExpression, it might be returning a result, which could be a mock function, rather thannull.
Suggested Fixes
You can update the mock of
modifyXPathExpressionto throw an error, or change the handling ingetXPathExpressionNodes. Let's modify the test to better simulate the error case:Modify the Test
Instead of having
modifyXPathExpressionreturn an error object, you can change it to throw an error:test('should return null when an error occurs', () => { const consoleSpy = jest.spyOn(console, 'log').mockImplementation(() => {}); const xmlString = '<data></data>'; const mockXMLDocument = new DOMParser().parseFromString(xmlString, 'application/xml'); (modifyXPathExpression as jest.Mock).mockImplementationOnce(() => { throw new Error('Error'); }); const result = getXPathExpressionNodes({ expression: '//group', xmlTree: mockXMLDocument, propagationIndex: 0, // assuming this value is necessary }); expect(result).toBeNull(); expect(consoleSpy).toHaveBeenCalledWith( 'Ошибка вычисления условия', expect.any(Error), '//group', ); consoleSpy.mockRestore(); // Restore the original console.log });Summary of Changes
- Change
mockReturnValueOnce(new Error('Error'))tomockImplementationOnce(() => { throw new Error('Error'); }). - Ensure the function signature in the test (
propagationIndex) includes all the required parameters forgetXPathExpressionNodes.
With these changes, the behavior of the mock should properly align with your expectations, and the test should pass as intended.
-
- User
import { type Propagation, XmlTreeCache } from '$conditions-core';
import { concatXmlTrees } from '../concatXmlTrees'; import { createXmlTreeFromJSON } from '../createXmlTreeFromJSON'; import { createXmlFromPropagations } from './createXmlFromPropagations';
interface CreateFullXmlProps { selectedPropagationIndex: number; productConditionsTreeXmlStr: string; propagations: Propagation[]; }
/**
-
Построение дерева из трёх деревьев: дерево продукта, дерево ковенанта, дерево активного распространения */ export const createFullXml = ({ selectedPropagationIndex, productConditionsTreeXmlStr, propagations, }: CreateFullXmlProps) => { const getPropagationId = (propagation: Propagation): string | null => propagation?.surety?.id || propagation?.scroll?.id || null;
const propagationsTree = createXmlFromPropagations(propagations);
const codesTrees = propagations.reduce( (acc, propagation, propagationIndex) => acc + createXmlTreeFromJSON({ attributes: propagation?.attributes, propagationId: getPropagationId(propagation), productAndCurrentCovenantTree: productConditionsTreeXmlStr + propagationsTree, propagationKindId: propagation.propagationKind?.id, propagationIndex, selectedPropagationIndex, }), '', );
const fullXml = concatXmlTrees(codesTrees + propagationsTree, productConditionsTreeXmlStr);
return XmlTreeCache.getXmlTreeFromString(fullXml); }; test('should create full XML from propagations', () => { const selectedPropagationIndex = 0;
const propagations: Propagation[] = [ { id: '1', partyId: 'party1', propagationKind: { id: 'kind1', label: 'Kind 1' }, propagationIndex: 0, guaranteeScroll: null, scroll: null, attributes: [], userTextSurety: null, userTextDocumentation: null, otherTypicalTextDocumentation: null, responsibilityMeasure: null, surety: { id: 'surety1', name: 'Surety 1' }, pledger: null, guarantor: null, selected: true, mandatory: false, nonStandard: false, byDefault: false, name: 'Propagation 1', userTextTypical: null, userTextDecision: null, partyForPropagation: null, }, { id: '2', partyId: 'party2', propagationKind: { id: 'kind2', label: 'Kind 2' }, propagationIndex: 1, guaranteeScroll: null, scroll: null, attributes: [], userTextSurety: null, userTextDocumentation: null, otherTypicalTextDocumentation: null, responsibilityMeasure: null, surety: { id: 'surety2', name: 'Surety 2' }, pledger: null, guarantor: null, selected: true, mandatory: false, nonStandard: false, byDefault: false, name: 'Propagation 2', userTextTypical: null, userTextDecision: null, partyForPropagation: null, }, ] as unknown as Propagation[]; (createXmlFromPropagations as jest.Mock).mockReturnValue( '<propagations><item>1</item><item>2</item></propagations>', ); (createXmlTreeFromJSON as jest.Mock).mockReturnValueOnce('<item1></item1>'); (createXmlTreeFromJSON as jest.Mock).mockReturnValueOnce('<item2></item2>'); const result = createFullXml({ selectedPropagationIndex, productConditionsTreeXmlStr, propagations, }); expect(createXmlFromPropagations).toHaveBeenCalledWith(propagations); expect(createXmlTreeFromJSON).toHaveBeenCalledTimes(2); expect(result).toBe(expect.any(Object));}); SecurityError: History object is associated with a document that is not fully active.
104 | 105 | expect(createXmlFromPropagations).toHaveBeenCalledWith(propagations);
106 | expect(result).toBe(expect.any(Object)); | ^ 107 | }); 108 | }); 109 |
-
- Assistant
The error you're encountering,
SecurityError: History object is associated with a document that is not fully active, typically occurs in a web environment when you try to interact with thewindow.historyobject in an invalid context (such as an isolated test environment) or if the tested code is attempting to manipulate or read from a document that's not completely loaded or active. However, in this context, it's hard to directly see why this error happens based solely on the test provided.Let’s try to address a few potential reasons and then offer some testing strategies to help you:
Potential Causes
-
Environment Issues: This error may be due to the test environment configuration. Ensure that your testing framework (Jest, React Testing Library, etc.) is appropriately set up to simulate a DOM environment (for example, using
jsdom). -
Mocking Related Functions: In the context of your function, ensure that while you are mocking
createXmlFromPropagationsandcreateXmlTreeFromJSON, all functions thatcreateFullXmlrelies upon are also either mocked or return expected values. -
Returned Value Checking:
expect(result).toBe(expect.any(Object));is incorrect for Jest'stoBe. You should useexpect.anything()to check if the result is an object, or check against a specific object shape. -
XML Parser Provisions: If the output of your function involves manipulating XML, ensure that the parsing methods are correctly mocked. If
XmlTreeCache.getXmlTreeFromString(fullXml)uses any DOM-related features, it will need to run in a proper DOM environment.
Suggested Changes
-
Check Jest Configuration: Ensure that you're using
jsdomas your test environment in your Jest configuration. It typically looks something like this:{ "testEnvironment": "jsdom", ... } -
Adjust the Result Expectation: Change your assertion to ensure it checks if the result is an instance of an object:
expect(result).toEqual(expect.any(Object)); -
Mock the Cache Function: If
XmlTreeCache.getXmlTreeFromStringis not a mocked function, it might invoke functionality that requires a fully active document. You should mock this function as well:(XmlTreeCache.getXmlTreeFromString as jest.Mock).mockReturnValue({/* mock object here, depending on what your code expects */}); -
Update the Test Case: Here’s how your updated test case might look:
import { XmlTreeCache } from '$conditions-core'; // Adjust the import based on your project structure import { createFullXml } from './createFullXml'; // Update with your actual path test('should create full XML from propagations', () => { const selectedPropagationIndex = 0; const propagations: Propagation[] = [ /* define populating test data */ ]; (createXmlFromPropagations as jest.Mock).mockReturnValue( '<propagations><item>1</item><item>2</item></propagations>', ); (createXmlTreeFromJSON as jest.Mock).mockReturnValueOnce('<item1></item1>'); (createXmlTreeFromJSON as jest.Mock).mockReturnValueOnce('<item2></item2>'); (XmlTreeCache.getXmlTreeFromString as jest.Mock).mockReturnValue({/* your mock object */}); const result = createFullXml({ selectedPropagationIndex, productConditionsTreeXmlStr: '', // Provide necessary input here propagations, }); expect(createXmlFromPropagations).toHaveBeenCalledWith(propagations); expect(createXmlTreeFromJSON).toHaveBeenCalledTimes(2); expect(result).toEqual(expect.any(Object)); });Conclusion
By adjusting mocks and ensuring the configuration is correct, you can reduce the chances of encountering errors while testing functions that manipulate or depend on the DOM. If the problem persists, you might want to isolate portions of the code or look for specific functions that are causing the issue directly within your overall test landscape.
-