如何在Jest测试中全局引用本地Kendo UI脚本
Hey there, let's tackle this Kendo UI global access issue in your React unit tests. I get that it works fine in the browser because you've included the script in index.html, but tests don't pick up that global automatically. Your current setupTests import didn't work—here are a few proven fixes to get Kendo globally available in your test environment:
1. Manually attach Kendo to the window object in setupTests
Kendo UI typically exposes itself on the browser's window object, but when importing it as an ES module, that automatic global attachment might not happen. Fix this by explicitly assigning it to window.kendo in your setupTests.js:
import * as kendo from '../public/scripts/kendo/kendo.all.min.js'; // Mount the imported Kendo object to the global window scope window.kendo = kendo;
This mirrors the browser's behavior, so your components can access kendo globally just like they do when running in the app.
2. Use require() instead of ES module imports
Kendo's kendo.all.min.js is a UMD (Universal Module Definition) file. When loaded via CommonJS require(), it automatically attaches itself to window—this might be more reliable than ES module imports for older UMD libraries:
// In setupTests.js require('../public/scripts/kendo/kendo.all.min.js');
No extra code needed here; the UMD wrapper handles the global attachment for you.
3. Ensure your setupTests file is loaded by your test runner
If you're using Jest (the most common test runner for React), double-check that your setupTests.js is configured to run before any tests. Update your jest.config.js (or the jest section in package.json) to include:
{ "jest": { "setupFilesAfterEnv": [ "<rootDir>/src/setupTests.js" ] } }
This guarantees that your Kendo global setup runs before any test files execute.
4. Mock the Kendo global (for lightweight tests)
If your tests don't need to use actual Kendo functionality (you just want to avoid "kendo is not defined" errors), you can mock a minimal kendo object instead of loading the full library:
// In setupTests.js window.kendo = { // Mock the specific Kendo features your components use, e.g.: ui: { DropDownList: jest.fn(), Grid: jest.fn() }, data: { DataSource: jest.fn() } };
This keeps your tests fast and avoids dependencies on external script files.
Start with method 2 first—it's the simplest and most likely to work for UMD libraries like Kendo. If that doesn't do the trick, try method 1 to force the global attachment.
内容的提问来源于stack exchange,提问作者Elijah1210

