Cypress拦截Nuxt后端API请求失败,尝试方案遇500错误
解决Nuxt后端发起的API请求无法被Cypress Mock的问题
问题核心
Cypress的cy.intercept仅能拦截浏览器端发起的请求,Nuxt后端(Node层)发起的请求无法被捕获,因此出现cy.wait()超时错误。你自定义的mockServer返回500错误,主要原因是响应头未正确设置,导致Nuxt后端无法解析返回的JSON数据。
解决方案一:修复自定义mockServer
修改cypress.config.ts中的mockServer任务,补充响应头、完善路径匹配和错误处理:
on("task", { mockServer({ interceptUrl, fixture }: { interceptUrl: string; fixture: string }) { const fs = require("fs"); const http = require("http"); const { URL } = require("url"); if (server) server.close(); const url = new URL(interceptUrl); server = http.createServer((req: any, res: any) => { // 用includes匹配路径,避免查询参数导致匹配失败 if (req.url.includes(url.pathname)) { try { const data = fs.readFileSync(`./cypress/fixtures/${fixture}`, 'utf8'); // 设置正确响应头,告知Nuxt返回的是JSON格式 res.writeHead(200, { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' // 跨域场景需添加 }); res.end(data); } catch (err) { // 读取文件失败时返回明确错误 res.writeHead(500); res.end(JSON.stringify({ error: 'Failed to load fixture' })); console.error('Mock server error:', err); } } else { // 非目标请求返回404 res.writeHead(404); res.end(); } }); server.listen(url.port, () => { console.log(`Mock server running on port ${url.port}`); }); return null; }, });
修改后确保conversations.json是有效JSON格式,再运行测试即可避免500错误。
解决方案二:利用Nuxt环境变量切换API源
- 在Nuxt项目中创建测试环境配置文件(如
.env.test):
NUXT_PUBLIC_API_BASE_URL=http://localhost:4000
- 在Nuxt的请求工具中使用该变量(以axios为例):
// plugins/axios.ts export default defineNuxtPlugin(() => { const config = useRuntimeConfig(); const axios = axios.create({ baseURL: config.public.apiBaseUrl }); return { provide: { axios } }; });
- 启动Cypress mockServer后,确保Nuxt指向该服务的地址,若端口一致则无需额外调整。
解决方案三:直接Mock Nuxt的请求方法
如果Nuxt使用$fetch或axios发起请求,可直接在测试中mock这些方法:
// 在测试的beforeEach或测试用例中 cy.window().then((win) => { // Mock Nuxt的$fetch get请求 cy.stub(win.$nuxt.$fetch, 'get') .withArgs('http://localhost:4000/conversations') .resolves(require('../fixtures/conversations.json')); }); cy.visit("http://localhost:3000/conversations"); // 直接断言页面内容,无需cy.wait cy.get('.conversation-item').should('have.length', 3); // 对应fixture中的数据条数
这种方法无需额外启动mock服务器,直接在浏览器端拦截Nuxt的请求逻辑。
内容的提问来源于stack exchange,提问作者FabienChn
相关产品推荐
相关产品推荐

