我正在尝试使用新的cypress 6拦截器方法(Cypress API Intercept)编写测试。对于我正在编写的测试,在执行某些操作后,我需要更改一个端点的响应。
期待:
我将使用另一个灯具再次调用cy.intercept,并期望它更改所有即将到来的呼叫以对此新灯具进行响应。
实际行为:
赛普拉斯仍会以该呼叫的第一个灯具为响应。
测试数据:
在一个测试项目中,我重新创建了问题:
test.spec.js
describe('testing cypress', () => {
it("multiple responses", () => {
cy.intercept('http://localhost:4200/testcall', { fixture: 'example.json' });
// when visiting the page it makes one request to http://localhost:4200/testcall
cy.visit('http://localhost:4200');
cy.get('.output').should('contain.text', '111');
// now before the button is clicked and the call is made again
// cypress should change the response to the other fixture
cy.intercept('http://localhost:4200/testcall', { fixture: 'example2.json' });
cy.get('.button').click();
cy.get('.output').should('contain.text', '222');
});
});
example.json
{
"text": "111"
}
example2.json
{
"text": "222"
}
app.component.ts
import { HttpClient } from '@angular/common/http';
import { AfterViewInit, Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
public text: string;
public constructor(private httpClient: HttpClient) { }
public ngAfterViewInit(): void {
this.loadData();
}
public loadData(): void {
const loadDataSubscription = this.httpClient.get<any>('http://localhost:4200/testcall').subscribe(response => {
this.text = response.body;
loadDataSubscription.unsubscribe();
});
}
}
app.component.html
<button class="button" (click)="loadData()">click</button>
<p class="output" [innerHTML]="text"></p>
稍显笨拙,但是你可以将其cy.intercept()
与Function routeHandler一起使用,并计算调用次数。
就像是,
let interceptCount = 0;
cy.intercept('http://localhost:4200/testcall', (req) => {
req.reply(res => {
if (interceptCount === 0 ) {
interceptCount += 1;
res.send({ fixture: 'example.json' })
} else {
res.send({ fixture: 'example2.json' })
}
});
});
否则,你的代码中的所有内容看起来都会很好,所以我认为目前不支持超越拦截是一项功能。
好的,我认为这对于cy.intercept()是有用的功能。感谢您的验证码!我已经尝试过了,还有一件小事丢失了。从拦截中我得到了请求,有了这个请求,我就可以按照您的建议来操纵响应。就我而言,这实际上是可行的。
let interceptCount = 0; cy.intercept('http://localhost:4200/testcall', (req) => { req.reply(res => { if (interceptCount === 0 ) { interceptCount += 1; res.send({ fixture: 'example.json' }) } else { res.send({ fixture: 'example2.json' }) } }); });
是的,您是对的,
req
控制res
。在花了几个小时试验OP想要的相同东西之后,我也使用了这种笨拙的方法。谢谢你的建议。