当您运行带有服务器端渲染的 Nuxt 应用程序时,会在服务器上进行 asyncData() 调用。
接收到的数据被添加到页面底部的“水化”功能,然后提供给赛普拉斯浏览器。所以cy.intercept() 永远不会接听电话。
处理它的一种方法是在测试期间模拟服务器,这可以在任务中完成
/cypress/plugins/index.js
let server; // static reference to the mock server
// so we can close and re-assign on 2nd call
module.exports = (on, config) => {
on('task', {
mockServer({ interceptUrl, fixture }) {
const fs = require('fs')
const http = require('http')
const { URL } = require('url')
if (server) server.close(); // close any previous instance
const url = new URL(interceptUrl)
server = http.createServer((req, res) => {
if (req.url === url.pathname) {
const data = fs.readFileSync(`./cypress/fixtures/${fixture}`)
res.end(data)
} else {
res.end()
}
})
server.listen(url.port)
console.log(`listening at port ${url.port}`)
return null
},
})
}
测试
const apiUrl = Cypress.env('api_url'); // e.g "http://localhost:9000"
cy.task('mockServer', { interceptUrl: `${apiUrl}/post`, fixture: 'post.json' })
cy.visit('/post')
// a different fixture
cy.task('mockServer', { interceptUrl: `${apiUrl}/post`, fixture: 'post2.json' })
cy.visit('/post')
cypress.json
{
"baseUrl": "http://localhost:3000",
"env": {
"api_url": "http://localhost:9000"
}
}
注意
- Nuxt 应用程序必须看到相同的
apiUrl
- 模拟服务器将始终是主机名:localhost
另一种方法
见Control Next.js Server-Side Data During Cypress Tests。
这个想法是在页面从服务器到达时拦截它并修改它的水合功能。
您让生产 API 服务器运行以进行测试,以便 SSR 正常获取。
function interceptHydration( interceptUrl, fixture, key ) {
cy.fixture(fixture).then(mockData => {
cy.intercept(
interceptUrl,
(req) => {
req.continue(res => {
// look for "key" in page body, replace with fixture
const regex = new RegExp(`${key}:\s*{([^}]*)}`)
const mock = `${key}: ${JSON.stringify(mockData)}`
res.body = res.body.replace(regex, mock)
})
}
)
})
}
it('changes hydration data', () => {
interceptHydration( '/post', 'post', 'post' )
cy.visit('/post')
cy.get('h1').contains('post #2') // value from fixture
})