@@ -117,35 +117,47 @@ describe("parseXml", () => {
117117
118118 describe ( "error handling" , ( ) => {
119119 it ( "wraps parser errors with a descriptive message" , ( ) => {
120- // Use jest.spyOn to mock the XMLParser implementation
120+ // Create a mock implementation that throws an error
121121 const mockParseFn = jest . fn ( ) . mockImplementation ( ( ) => {
122122 throw new Error ( "Simulated parsing error" )
123123 } )
124124
125+ // Create a mock parser instance
125126 const mockParserInstance = {
126127 parse : mockParseFn ,
127128 }
128129
129- // Spy on the XMLParser constructor to return our mock
130- const parserSpy = jest
131- . spyOn ( require ( "fast-xml-parser" ) , "XMLParser" )
132- . mockImplementation ( ( ) => mockParserInstance )
133-
134- // Test that our function wraps the error appropriately
135- expect ( ( ) => parseXml ( "<root></root>" ) ) . toThrow ( "Failed to parse XML: Simulated parsing error" )
136-
137- // Verify the parser was called with the expected options
138- expect ( parserSpy ) . toHaveBeenCalledWith ( {
139- ignoreAttributes : false ,
140- attributeNamePrefix : "@_" ,
141- parseAttributeValue : false ,
142- parseTagValue : false ,
143- trimValues : true ,
144- stopNodes : [ ] ,
130+ // Create a mock constructor function
131+ const MockXMLParser = jest . fn ( ) . mockImplementation ( ( ) => mockParserInstance )
132+
133+ // Save the original XMLParser
134+ const { XMLParser } = jest . requireActual ( "fast-xml-parser" )
135+
136+ // Replace the XMLParser with our mock
137+ jest . doMock ( "fast-xml-parser" , ( ) => ( {
138+ XMLParser : MockXMLParser ,
139+ } ) )
140+
141+ // Import the module with our mocked dependency
142+ jest . isolateModules ( ( ) => {
143+ const { parseXml } = require ( "../xml" )
144+
145+ // Test that our function wraps the error appropriately
146+ expect ( ( ) => parseXml ( "<root></root>" ) ) . toThrow ( "Failed to parse XML: Simulated parsing error" )
147+
148+ // Verify the parser was called with the expected options
149+ expect ( MockXMLParser ) . toHaveBeenCalledWith ( {
150+ ignoreAttributes : false ,
151+ attributeNamePrefix : "@_" ,
152+ parseAttributeValue : false ,
153+ parseTagValue : false ,
154+ trimValues : true ,
155+ stopNodes : [ ] ,
156+ } )
145157 } )
146158
147- // Cleanup
148- parserSpy . mockRestore ( )
159+ // Restore the original module
160+ jest . dontMock ( "fast-xml-parser" )
149161 } )
150162 } )
151163} )
0 commit comments