如何在jsdom中用相对路径加载HTML文件?相对路径失效问题
The problem here is that relative paths in JSDOM.fromFile are resolved against the current working directory (CWD) of your test process, not the directory where your test file is located. Even if your relative path looks correct from the test file's perspective, if your test runner (like Mocha) is executing from a different folder, it won't find the HTML file.
The Solution: Use __dirname with the path Module
__dirname is a Node.js global that always refers to the directory of the current module (your test file). By combining it with path.join (or path.resolve), you can create a portable, absolute path that works regardless of where you run your tests.
Here's how to adjust your code:
- First, require the Node.js
pathmodule at the top of your test file:
const path = require('path');
- Modify your
beforehook to build the file path using__dirname:
before(function(done) { // Build the absolute path relative to this test file's directory const htmlFilePath = path.join(__dirname, '../../../src/main/resources/templates/components/xyz.html'); JSDOM.fromFile(htmlFilePath) .then((dom) => { global.document = dom.window.document; }) .then(done, done); });
Why This Works
path.joinautomatically handles cross-platform path separators (like/vs\), so your code will work on Windows, macOS, and Linux.__dirnameensures the path is resolved relative to your test file, not the process's working directory. This avoids issues if you run your tests from a subfolder or root folder of your project.
Debugging Tip
If you're still having trouble, log the generated file path to verify it matches the absolute path that works:
console.log('Resolved file path:', htmlFilePath);
This will show you exactly where Node.js is looking for the file, so you can adjust the number of ../ segments if needed.
内容的提问来源于stack exchange,提问作者praveen

