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

Angular环境下Cypress组件测试中assets文件夹404问题求助

解决方案

1. 修正Cypress配置的根目录与资源路径

在cypress.config.ts的projectConfig中,将root设置为项目根目录(.),确保assets路径能被正确解析:

component: {
  devServer: {
    framework: 'angular',
    bundler: 'webpack',
    options: {
      projectConfig: {
        root: '.', // 改为项目根目录
        sourceRoot: 'src',
        buildOptions: {
          // ... 其他原有配置
          assets: [
            "src/favicon.ico",
            "src/assets",
          ],
          // ... 其他原有配置
        }
      }
    }
  },
  // ... 其他配置
}

2. 指定Cypress静态资源目录

在Cypress根配置中添加fileServerFolder,让Cypress能直接访问项目根目录下的资源:

export default defineConfig({
  component: {
    // ... 现有配置
    fileServerFolder: '.', // 添加此行
    specPattern: '**/*.cy.ts',
  },
})

3. 手动导入全局样式(解决node_modules样式不生效)

在自定义的mount命令文件中,直接导入全局样式文件,确保组件测试环境加载所需样式:

// cypress/support/component.ts
import { mount } from 'cypress/angular';
// 导入项目全局样式和第三方依赖样式
import '../../src/styles.scss';
import '@angular/material/_theming.scss';
import '../../node_modules/.../scss/material-theme/main.scss'; // 替换为实际路径

declare global {
  namespace Cypress {
    interface Chainable {
      mount: typeof mount;
    }
  }
}

Cypress.Commands.add('mount', mount);

4. 检查组件模板的资源路径

确保component.index.html中引用assets的路径为绝对路径,避免相对路径解析错误:

<!-- cypress/support/component.index.html -->
<img src="/assets/img/sun.jpg" alt="Sun">
<script src="/assets/i18n/fr.json"></script>

5. 自定义Webpack配置复制资源(可选)

如果以上方法无效,通过copy-webpack-plugin手动复制assets到测试服务器目录:

  1. 安装依赖:
npm install copy-webpack-plugin --save-dev
  1. 修改Cypress配置:
import CopyPlugin from 'copy-webpack-plugin';

component: {
  devServer: {
    framework: 'angular',
    bundler: 'webpack',
    webpackConfig: {
      plugins: [
        new CopyPlugin({
          patterns: [
            { from: 'src/assets', to: 'assets' },
          ],
        }),
      ],
    },
    // ... 现有options配置
  },
}

内容的提问来源于stack exchange,提问作者Samantha Létourneau

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 12:03:09