使用截取更改同一url的cypress中的夹具响应

我正在尝试使用新的 cypress 6 拦截器方法(Cypress API Intercept)编写测试。对于我正在编写的测试,我需要在执行某些操作后更改一个端点的响应。

期待:

我用另一个装置再次调用 cy.intercept 并期望它改变所有即将到来的调用以响应这个新装置。

实际行为:

赛普拉斯仍然使用为呼叫设置的第一个夹具来响应。

测试数据:

在一个测试项目中,我重新创建了这个问题:

测试规范.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');
        
    });

});

例子.json

{
  "text": "111"
}

示例2.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();
    });
  }

}

应用程序组件.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' })
    }
  }); 
});

否则,您的代码中的一切看起来都不错,所以我猜此时覆盖拦截不是一项功能。

  • After spending hours experimenting the same thing OP wants, I ended up here using this clumsy way too. Thanks for the suggestion.

以上是使用截取更改同一url的cypress中的夹具响应的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>