实例化Touch时报TypeError:构造函数需1个参数但传入0个的问题
Let’s resolve that annoying error you’re facing in your getComponent function tests. The root cause is clear: the native Touch constructor demands a single configuration object with mandatory properties—calling new Touch() without any arguments violates this requirement, which is why your tests at lines 166 and 170 of D:/ej2-base-library/spec/base.spec.js are failing.
Here are two reliable fixes to get your tests passing:
1. Properly Instantiate the Touch Object
The Touch constructor needs a TouchInit object with at least two core properties: identifier (a unique numeric ID for the touch) and target (the DOM element the touch is interacting with). You can create a mock DOM element and pass the required parameters like this:
// Create a mock DOM element to use as the touch target const mockTouchTarget = document.createElement('div'); // Correctly initialize the Touch object with required properties const validTouch = new Touch({ identifier: 1, // Unique ID for the touch event target: mockTouchTarget, // The element being touched clientX: 50, // Optional: Add coordinates if your component uses them clientY: 50 });
Replace every instance of new Touch() in your test code with this properly configured version, and the parameter error should disappear.
2. Mock the Touch Class for Jest’s jsdom Environment
Sometimes Jest’s jsdom environment doesn’t fully replicate the browser’s Touch API. If you still run into issues after proper instantiation, you can mock the Touch class entirely to avoid relying on the native implementation:
// Add this at the top of your test file or inside a beforeEach block global.Touch = class MockTouch { constructor(options) { // Mirror the properties your component actually uses this.identifier = options.identifier; this.target = options.target; this.clientX = options.clientX || 0; this.clientY = options.clientY || 0; } };
This custom mock gives you full control over the Touch object’s behavior, ensuring your tests don’t depend on jsdom’s incomplete API support.
Quick Check: Verify DOM Setup
Make sure your test cases create the necessary DOM elements (like the mock target above) before instantiating the Touch object. Jest won’t automatically set up a full browser DOM, so you’ll need to manually create any elements your touch events rely on.
内容的提问来源于stack exchange,提问作者Vijay VJ

