英文:
How can I stub a server side response via cypress?
问题
I'm running a react project that returns html in the response of the network call (server side rendering). I wanted to stub the html response for testing however I'm not sure how that would work.
Here's what I've tried:
it("Example test", () => {
cy.intercept('GET', '/some-network-call', {
statusCode: 200,
body: html
}).as('mockedResponse');
cy.visit("http://localhost:3000");
cy.wait('@mockedResponse').then(() => {
cy.screenshot("Test Screenshot");
});
});
The intercept indeed does its job, however, the output just breaks the rendered app.
The Cypress docs mention you can stub things like the header, body, statuscode, etc. Is there a good way to simulate server side calls that return html responses?
英文:
I'm running a react project that returns html in the response of the network call (server side rendering). I wanted to stub the html response for testing however I'm not sure how that would work.
Here's what I've tried:
it("Example test", () => {
cy.intercept('GET', '/some-network-call', {
statusCode: 200,
body: html
}).as('mockedResponse');
cy.visit("http://localhost:3000");
cy.wait('@mockedResponse').then(() => {
cy.screenshot("Test Screenshot");
});
});
The intercept indeed does its job, however, the output just breaks the rendered app.
The Cypress docs mention you can stub things like the header, body, statuscode, etc. Is there a good way to simulate server side calls that return html responses?
答案1
得分: 3
如果拦截器正常工作(cy.wait('@mockedResponse')
没有超时),那么严格来说,这不是服务器端渲染 - 至少不是那个特定的调用。
但是语义不管,看起来 body: html
不正确,不管 html
是什么。
为了确切了解服务器提供了什么内容,暂时移除模拟响应,并通过 cy.wait('@mockedResponse')
捕获服务器的响应,然后相应地修改你的存根。
it("示例测试", () => {
cy.intercept('GET', '/some-network-call').as('mockedResponse');
cy.visit("http://localhost:3000");
cy.wait('@mockedResponse').then(interception => {
console.log(interception.response) // 查看应用程序从实时服务器看到的内容,然后根据此内容修改模拟
});
});
英文:
If the intercept is working (cy.wait('@mockedResponse')
is not timing out), then strictly speaking it's not server-side rendering - at least not that particular call.
But semantics aside, it looks like body: html
is not correct, whatever html
is.
To find out exactly what the server is serving up, temporarily remove the mock response and capture the server's response via cy.wait('@mockedResponse')
, then modify your stub accordingly.
it("Example test", () => {
cy.intercept('GET', '/some-network-call').as('mockedResponse');
cy.visit("http://localhost:3000");
cy.wait('@mockedResponse').then(interception => {
console.log(interception.response) // take a look at what the app sees
// from the live server, base your mock on that
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论