Warm tip: This article is reproduced from serverfault.com, please click

angular-用intercept更改赛普拉斯中相同URL的灯具响应

(angular - Change fixture response in cypress for the same url with intercept)

发布于 2020-11-27 22:56:43

我正在尝试使用新的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>
Questioner
S. Hick
Viewed
11
Richard Matsen 2020-11-29 03:01:06

稍显笨拙,但是你可以将其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' })
    }
  }); 
});

否则,你的代码中的所有内容看起来都会很好,所以我认为目前不支持超越拦截是一项功能。