1

At this point I am stubbing API endpoints with Cypress Intercept. It is working great, but I've the feeling I could use it more efficient.

Currently I have the following test:

 cy.intercept('GET', '**/Classifications', { fixture: 'stubClassifications/Classifications5.json' })
        cy.get('div.dropdown-menu.show').find('a.dropdown-item').should('have.length', 5)

It's working, and checks the file Classifications5.json where 5 classifications are available.:

enter image description here

Classifications5.json:

 [
  {
    "id": "6a75b703-8af4-4734-8d3f-c259d36b7a5e",
    "name": "1STUBTest EEO",
    "hasChildren": false
  },

  {
    "id": "6a75b703-8af4-4734-8d3f-c259d36b7a5e",
    "name": "2STUBTest EEO",
    "hasChildren": false
  },

  {
    "id": "6a75b703-8af4-4734-8d3f-c259d36b7a5e",
    "name": "3STUBTest EEO",
    "hasChildren": false
  },
  {
    "id": "6a75b703-8af4-4734-8d3f-c259d36b7a5e",
    "name": "4STUBTest EEO",
    "hasChildren": false
  },
  {
    "id": "6a75b703-8af4-4734-8d3f-c259d36b7a5e",
    "name": "5STUBTest EEO",
    "hasChildren": false
  }
]

In a following test I am stubbing the same API-endpoint but with just 1 classification, namely Classifications1.json.

As you can understand I made several .json file in the fixture map for each result that I am asserting and this doesn't look very nice and clean.

How can I prevent making multiple .json files in the map fixtures when using the cy.intercept for the same end-point.

Fody
  • 23,754
  • 3
  • 20
  • 37
E. E. Ozkan
  • 149
  • 10

1 Answers1

0

It seems like you are saying that Classifications1.json is a smaller version of Classifications5.json?

If so you only need the Classifications5.json file. Smaller files can be derived from it.

cy.fixture('Classifications5.json').then(fiveItems => 
  const oneItem = fiveItems.slice(0,1)
  cy.intercept('GET', '**/Classifications', oneItem)

In a two-item test

cy.fixture('Classifications5.json').then(fiveItems => 
  const twoItems = fiveItems.slice(0,2)
  cy.intercept('GET', '**/Classifications', twoItems)

Generating the fixture

If the only thing that changes is the name property, you could generate the fixture on the fly.

const generateFixture = (numItems) => {
  const fixture = [...Array(numItems).keys()].map(key => {
    return {
      id: "6a75b703-8af4-4734-8d3f-c259d36b7a5e",
      name: `${key}STUBTest EEO`,
      hasChildren: false
    }
  })
  return fixture
}

...

const twoItems = generateFixture(2)
cy.intercept('GET', '**/Classifications', twoItems)
Fody
  • 23,754
  • 3
  • 20
  • 37
  • Hi Fody! Thanks for your amazing answer :) .slice method seems to work. But your second solution gives me the following error: "Array(...).keys(...).Map is not a function" What would be the solution for this? Because this really looks a nice and effective method. – E. E. Ozkan Jun 21 '22 at 09:18
  • 1
    Sorry I missed some brackets. – Fody Jun 21 '22 at 20:42