You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在jsdom中用相对路径加载HTML文件?相对路径失效问题

Fixing Relative Path Issues with JSDOM.fromFile

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:

  1. First, require the Node.js path module at the top of your test file:
const path = require('path');
  1. Modify your before hook 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.join automatically handles cross-platform path separators (like / vs \), so your code will work on Windows, macOS, and Linux.
  • __dirname ensures 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 08:44:26