Home > Net >  How to Receive cypress interception fixture twice but in different format?
How to Receive cypress interception fixture twice but in different format?

Time:07-26

I'm a beginner with Cypress and I am stuggeling with the following:

I am calling the following from my test file:

cy.SetupClassificationsStubFixture(1);

This refers to the following command:

Cypress.Commands.add("SetupClassificationsStubFixture", (amount) => {

cy.fixture('ClassificationsStub.json').then(classificationsStub => {
    const slicedClassifications = classificationsStub.slice(0, amount)
    cy.intercept('GET', '**/api/classifications', slicedClassifications)
}).as('classifications')


cy.fixture('ClassificationsStub.json').then(classificationsStub => {
    const slicedClassifications = classificationsStub.slice(0, amount)
    cy.intercept('GET', '**/api/classifications/*', slicedClassifications)
}).as('classifications') });

As you can see this customcommand is intercepting 2 api request. Namely:

  1. ** /api/classifications
  2. ** /api/classifications/ *

The first interception is with [] The second intercecption needs exactly the same response buth without brackets []

But you already understand that both respons are now with brackets '[]'. I tried to make a second fixture file without [], but the the slice function is not working.

So I need: The second intercept like:

{
    "id": "9d4a9c14-ef37-4a64-a1eb-63ab45cdf530",
    "name": "CypressTest",
    "userRole": "Editor",
    "childClassifications": []
}

But I get:

[{
    "id": "9d4a9c14-ef37-4a64-a1eb-63ab45cdf530",
    "name": "CypressTest",
    "userRole": "Editor",
    "childClassifications": []
}]

How could I get this array back without []? Thankyou indeed!

CodePudding user response:

There looks to be some brackets out of place in the code.

I would also recommend using different alias names, otherwise the calls to cy.wait('@classifications') may not work as you expect.

Cypress.Commands.add("SetupClassificationsStubFixture", (amount) => {

  cy.fixture('ClassificationsStub.json').then(classificationsStub => {

    const slicedClassifications = classificationsStub.slice(0, amount)
    cy.intercept('GET', '**/api/classifications', slicedClassifications)
      .as('classifications')

    const firstClassification = slicedClassifications[0]  // just first item
    cy.intercept('GET', '**/api/classifications/*', firstClassification)
      .as('firstClassification') 

  })
});

CodePudding user response:

So in case, your data looks like this:

var data = [{
    "id": "9d4a9c14-ef37-4a64-a1eb-63ab45cdf530",
    "name": "CypressTest",
    "userRole": "Editor",
    "childClassifications": []
}]

So to extract the data with just curly braces you can do data[0].

{
    "id": "9d4a9c14-ef37-4a64-a1eb-63ab45cdf530",
    "name": "CypressTest",
    "userRole": "Editor",
    "childClassifications": []
}

Working example console screenshot:

console sccreenshot

  • Related