TestCafe无法加载基准URL(登录页),页面空白且报MIME类型错误
TestCafe加载基准URL空白页问题排查
问题概述
TestCafe无法加载指定的登录页面基准URL,访问时仅显示空白页面,关键信息如下:
- 普通浏览器可正常访问该登录页面
- TestCafe Studio录制时同样复现此问题
- 使用官方示例URL(
https://devexpress.github.io/testcafe/example)测试无异常
测试代码
fixture('Getting Started') .page('https://base_url/RRApp/auth/login'); test('My first test', async t => { await t .debug() .typeText('#developer-name', 'John Smith') .click('#submit-button'); });
控制台错误详情
:51582/HeWNWihUP*hTz…d054cfa21e2582.js:1 Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec. :51582/HeWNWihUP*hTz…ac00f42bc3886e.js:1 Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec. :51582/HeWNWihUP*hTz…08841904c1a9ce.js:1 Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec. scripts.84ac6b0981f52dfb.js:1 Uncaught SyntaxError: Unexpected token '<'
排查方向与解决方案
- 代理路径冲突处理:TestCafe通过代理加载页面资源,目标站点的路由规则或资源路径可能与代理机制冲突,导致JS模块请求被返回HTML页面。可尝试:
- 使用
--hostname参数指定代理主机,确保资源请求路径正确解析 - 通过
--proxy配置自定义代理规则,映射站点资源路径
- 使用
- 调整内容安全策略(CSP):站点的CSP规则可能阻止TestCafe注入的脚本执行。在测试代码中添加CSP兼容配置:
fixture('Getting Started') .page({ url: 'https://base_url/RRApp/auth/login', clientScripts: { contentSecurityPolicy: "script-src 'self' 'unsafe-inline' 'unsafe-eval';" } }); - 模拟浏览器请求头:部分站点会根据请求头返回不同内容,TestCafe的默认请求头可能被服务器识别为非浏览器请求。使用
RequestHook修改请求头:import { RequestHook } from 'testcafe'; class ModifyHeadersHook extends RequestHook { constructor() { super(); } async onRequest(event) { event.requestOptions.headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'; } async onResponse(event) {} } const modifyHeadersHook = new ModifyHeadersHook(); fixture('Getting Started') .page('https://base_url/RRApp/auth/login') .requestHooks(modifyHeadersHook); - 升级TestCafe版本:旧版本TestCafe可能存在与现代JS模块加载机制的兼容性问题,升级到最新稳定版本尝试解决。
内容的提问来源于stack exchange,提问作者Janesh Kodikara
相关产品推荐
相关产品推荐

