skip to Main Content

Hey so I’m test react app with cypress and having a fake api with json-server.

When I run some of the test, it will change the datebase my db.json file.

So the plan was to restore the database after each test to the original.

Here’s my code:

describe('Testing fake db to be restored to original database after 
updating it in other test', () => {

 let originalDb: any = null

    it('Fetch the db.json file and then updating it to the original copy', 
       () => {

      // Save a copy of the original database
      cy.request('GET', 'localhost:8000/db').then(response => {
         originalDb = response;
         console.log(originalDb);
       })

    // Restore the original database
    cy.wrap(originalDb).then(db => {
      cy.request({
        method: 'PUT',
        url: 'http://localhost:8000/db',
        headers: {
          'Content-Type': 'application/json',
        },
        body: originalDb
      });
    });
  })
})

The code seems to work with getting the db(the hole db.json file)

But not able to make the put request. here are the error from cypress:

cy.request() failed on:



http://localhost:8000/db



The response we received from your web server was:



  > 404: Not Found



This was considered a failure because the status code was not 2xx or 3xx.



If you do not want status codes to cause failures pass the option: failOnStatusCode: false



-----------------------------------------------------------



The request we sent was:



Method: PUT

URL: http://localhost:8000/db

Headers: {

  "Connection": "keep-alive",

  "Content-Type": "application/json",

  "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36",

  "accept": "/",

  "accept-encoding": "gzip, deflate",

  "content-length": 29554

}

Body: {"body":{"users":[{"id":1,"first_name":"Gustav","last_name":"Vingtoft","fullname":"Gustav Vingtoft","email":"[email protected]","email_verified_at":"2023-01-25T12:13:02.000000Z","created_at":"2023-01-25T12:13:02.000000Z","updated_at":"2023-01-25T12:13:02.000000Z","api_token":"$2y$10$dtYPv.E0zua15DAvvvUQve0XdB77yo.4r.vMaiDOezKZrG7TugG9G","companyName":"Deloitte Denmark","phone":"+4530934268","userProfile":"basic","userRole":"reviewer","riskPatterns":[{"patternUuid":"04bdcd7b-d61b-45cc-b9ea-c2decc77c852"},{"patternUuid":"1b3d8a0f-2bc3-4c50-a00a-6cf99335dd20"}],"pic":"/media/users/Gustav_Vingtoft.jpg"},{"id":2,"first_name":"Frederik","last_name":"Nielsen","fullname":"Frederik Nielsen","email":"[email protected]","email_verified_at":"2023-01-25T12:13:02.000000Z","created_at":"2023-01-25T12:13:02.000000Z","updated_at":"2023-01-25T12:13:02.000000Z","api_token":"$2y$10$dtYPv.E0zua15LKSDFVKXdB77yo.4r.vMaiDOezKZrG7TugG9G","companyName":"Deloitte Denmark","phone":"+4511223344","userProfile":"basic","userRole":"reviewer","riskPatterns":[{"patternUuid":"04bdcd7b-d61b-45cc-b9ea-c2decc77c852"}],"pic":"/media/users/Frederik_Nielsen.jpeg"},{"id":3,"first_name":"David","last_name":"Mortensen","fullname":"David Mortensen","email":"[email protected]","email_verified_at":"2023-01-25T12:13:02.000000Z","created_at":"2023-01-25T12:13:02.000000Z","updated_at":"2023-01-25T12:13:02.000000Z","api_token":"$2y$10$dtYPv.E0zSDGKOJSGFJLDVVSve0XdB77yo.4r.vMaiDOezKZrG7TugG9G","companyName":"Deloitte Denmark","phone":"+4511225544","userProfile":"basic","userRole":"investigator","riskPatterns":[{"patternUuid":"04bdcd7b-d61b-45cc-b9ea-c2decc77c852"}],"pic":"/media/users/300-9.jpg"},{"id":4,"first_name":"test","last_name":"test","fullname":"test user","email":"[email protected]","email_verified_at":"2023-01-25T12:13:02.000000Z","created_at":"2023-01-25T12:13:02.000000Z","updated_at":"2023-01-25T12:13:02.000000Z","api_token":"$2y$10$dtYPv.E0zfghvcvssSve0XdB77yo.4r.vMaiDOezKZrG7TugG9G","companyName"...



-----------------------------------------------------------



The response we got was:



Status: 404 - Not Found

Headers: {

  "x-powered-by": "Express",

  "vary": "Origin, Accept-Encoding",

  "access-control-allow-credentials": "true",

  "cache-control": "no-cache",

  "pragma": "no-cache",

  "expires": "-1",

  "x-content-type-options": "nosniff",

  "content-type": "application/json; charset=utf-8",

  "content-length": "2",

  "etag": "W/"2-vyGp6PvFo4RvsFtPoIWeCReyIC8"",

  "date": "Mon, 24 Apr 2023 15:43:45 GMT",

  "connection": "keep-alive",

  "keep-alive": "timeout=5"

}

Body: {}

3

Answers


  1. Chosen as BEST ANSWER

    So for those of you that what to save a copy of your json-server db before making test an manipulate with an restore it to original. You can do it without the cy.request and jsut use cy.readFile and cy.writeFile heres a basic example:

     let originalDb = null;
    
      beforeEach(() => {
        // Read the current database state and write it to a backup file
        cy.readFile('db.json').then(db => {
          originalDb = db;
          cy.writeFile('db.json.backup', originalDb);
        });
      });
    
      it('easy test', () => {
        cy.visit('localhost:3000')
      })
    
      afterEach(() => {
        // Restore the backup file to the database
        cy.readFile('db.json.backup').then(db => {
          cy.writeFile('db.json', db);
        });
      });
    

  2. By default, with json-server, you don’t have a POST or PUT request at the root /db

    Login or Signup to reply.
  3. Your code is acting too soon – the request to localhost:8000/db is still in progress when to issue the next request with PUT.

    You need to (at minimum) add a .then() to sequence the requests correctly.

    let originalDb: any = null
    
    // Save a copy of the original database
    cy.request('GET', 'localhost:8000/db').then(response => {
      originalDb = response;
      console.log(originalDb);
    })
    .then(() => {
      // Restore the original database
      cy.wrap(originalDb).then(db => {
      cy.request({
        method: 'PUT',
        url: 'http://localhost:8000/db',
        headers: {
          'Content-Type': 'application/json',
        },
        body: originalDb
      });
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search