I am beginning to add tests to my TypeScript web application using Jest. Some functions (or methods) use the SVG API and interact with the DOM. I installed:
- jest
- @types/jest
- jest-environment-jsdom, and
- ts-jest
A lot of the SVG APIs are not supported by Jest, resulting in test errors such as TypeError: ... is not a function. jointJS provides a "setup" file creating some mocks to address the missing functionality in JSDOM. It appears if I want to test my functions/methods that interact with the SVG API, I'll have to add mock after mock to address every error I encounter related to missing SVG API functionality. Is there a better way to test code that interacts with the SVG API?
If not, my feeling is to isolate all code that interacts with the SVG API, and not test it. Rather than trying to add functionality to Jest.
Below is an example of one of my methods that creates a path element and adds it to the DOM.
/** * Creates an {@link SVGPathElement}. * @param id The element identifier. * @param parentId The parent element identifier. * @returns An {@link SVGPathElement}. */ public static createPathElement(id: string, parentId: string): SVGPathElement { let parent: SVGElement = document.querySelector(QueryById(parentId)); let element: SVGPathElement = document.querySelector(QueryById(id)); if (parent == null) parent = document.querySelector(ElementType.svg); if (element == null) { element = document.createElementNS(Constants.svg_ns, ElementType.path); element.setAttribute(Attribute.id, id); parent.appendChild(element); } // If element does not have a transform matrix, add it. if (element.transform == null || element.transform.baseVal.length == 0) { let svg: SVGSVGElement = element.ownerSVGElement; let transform: SVGTransform = svg.createSVGTransform(); element.transform.baseVal.appendItem(transform); } return element; } The first error I receive is addressed with joinJS's setup file:
TypeError: svg.createSVGTransform is not a function 73 | if (element.transform == null || element.transform.baseVal.length == 0) { 74 | let svg: SVGSVGElement = element.ownerSVGElement; > 75 | let transform: SVGTransform = svg.createSVGTransform(); | ^ 76 | element.transform.baseVal.appendItem(transform); 77 | } 78 | However, the next error occurs because there is likely no support for the SVGAnimatedTransformList.
TypeError: Cannot read properties of undefined (reading 'baseVal') 74 | let svg: SVGSVGElement = element.ownerSVGElement; 75 | let transform: SVGTransform = svg.createSVGTransform(); > 76 | element.transform.baseVal.appendItem(transform); | ^ 77 | } 78 | 79 | return element;
<circle>is actually a circle and not oval shaped? My point being; when you buy a car do you test the tire pressure is correct? Do you test a<select>for not displaying its<option>list halfway outside the viewPort? Do you test what happends when a<textarea>exceeds its character limit? Do you test the contrast of every text against its background color?