Luna
Luna

Reputation: 331

How improve test case that it will run before my other test cases in cypress API

I have setUpDB.spec.js file which is for setting up the database. I need this spec.js to be run before my other test cases. Can you please help me solve it? Thank you so much.

setUpDB.spec.js

describe('POST method', () => {
  it('it is for setup data',()=> {
    cy.request({
        method: 'POST',
        url:"xxxx:{
            "Authorization":"LOOL",
            "content-type": "application/json"
        },
        body: {
            "test-case": "base"
        },
        failOnStatusCode: false
    })
        .then((res) => {
            expect(res.status).to.eq(200)
        })
   })
})`

and another test case

describe('POST method', () => {
  it('aaa', () => {

    cy.request({
        method: 'POST',
        url:"https:xxxx",

        headers:{
            "Authorization":"LOOL",
            "content-type": "application/json"
        },

        body: {
            "id": "blabla",
            "bid": 10,
            "auctionPlatformId": "wwww",
            "auctionPlatformUserId": 0
        },

        failOnStatusCode: false

        
    })
        .then((res) => {
            expect(res.status).to.eq(200)
            expect(res.body).to.have.property("id", "blabla")
            expect(res.body).to.have.property("price", 10)
            expect(res.body).to.have.property("winningBidPlatformId", "www")
            expect(res.body).to.have.property("winningBidPlatformUserId", 0)

            // assert
            assert.isNotNull(res.body.id, 'is not null')
            assert.isNotNull(res.body.createdAt, 'is not null')
        })
}) 
})

Upvotes: 1

Views: 106

Answers (1)

Seeker
Seeker

Reputation: 455

Did you consider running the "setup data" request in a beforeEach()?

beforeEach(()=> {
  cy.request({
    method: 'POST',
    url:"xxxx:{
      "Authorization":"LOOL",
      "content-type": "application/json"
    },
    body: {
     "test-case": "base"
    },
    failOnStatusCode: false
  })
  .then((res) => {
    expect(res.status).to.eq(200)
  })
})

it('uses setup data', () => {
  ...

If the setup procedure is a one-shot call (can't be repeated), try using a cy.session() wrapper.

This wrapper acts like a cache, so the inner request is only called once, but it's side effects like cookies, localStorage are reinstated every time beforeEach() is called.

Cypress.config('experimentalSessionSupport', true)

beforeEach(()=> {
  cy.session('setup-data', () => {   
    cy.request({
      method: 'POST',
      url:"xxxx:{
        "Authorization":"LOOL",
        "content-type": "application/json"
      },
      body: {
       "test-case": "base"
      },
      failOnStatusCode: false
    })
    .then((res) => {
      expect(res.status).to.eq(200)
    })
  })
})

it('uses setup data', () => {
  ...

Upvotes: 3

Related Questions