TestCafe TypeScript测试中导入SCSS模块无法解析的问题如何解决?
TestCafe 1.17.1 SCSS模块解析问题处理
问题背景
在1.17.1版本的TestCafe中编写测试用例时,出现TypeScript编译阶段的模块解析错误。
相关代码
- 测试文件路径:
<root>/tests/test.e2e.ts
//test.e2e.ts in <root>/tests folder import {MyComponent} from '../src/MyComponent'; ... fixture('Custom domain tests'); test('test 1', async () => { ... });
- 组件文件路径:
<root>/src/MyComponent.tsx
//MyComponent.tsx in <root>/src folder import React, { FunctionComponent } from 'react'; import styles from '../scss/MyComponent.module.scss'; export const MyComponent: FunctionComponent = () => { ... }
报错信息
执行testcafe ./tests/test.e2e.ts命令时返回如下错误:Error: TypeScript compilation failed. Cannot find module '../scss/MyComponent.module.scss' or its corresponding type declarations.
已尝试的解决方法
- 配置paths映射:在根目录下新建
scss-module-for-tests.ts文件,仅导出空字符串,同时在.testcaferc.json中添加如下配置:
// .testcaferc.json in <root>/ { "compilerOptions": { "typescript": { "options": { "esModuleInterop": true, "baseUrl": ".", "paths": { "../scss/MyComponent.module.scss": ["scss-module-for-tests.ts"], "*.scss": ["scss-module-for-tests.ts"] } } } } }
但TypeScript的paths配置不支持相对路径解析和正则匹配,项目内存在大量../scss/*module.scss格式的导入语句,无法通过该方式批量处理。
2. 调整esModuleInterop配置:2021年12月2日调整.testcaferc.json配置如下,但esModuleInterop=true未生效:
//.testcaferc.json at <root> { "compilerOptions": { "typescript": { "options": { "esModuleInterop": "true" } } } }
最终解决方案
2021年12月13日更新:因配置复杂度较高,最终移除测试代码中所有对*.scss文件的引用,问题已解决。
内容的提问来源于stack exchange,提问作者thusimon
相关产品推荐
相关产品推荐

