How to change property of a record in db with cypress.io

瘦欲@ 提交于 2020-01-05 07:19:06

问题


i'm new to cypress and i'm wondering how can i do the following checks: I have case: I have a product in the db, that can have statuses: InStock and OutOfStock and Discontinued. If product is in 'InStock ' status, i should be able to dispatch it to a customer, if in 'OutOfStock'/ 'Discontinued' i should not be able to dispatch to a customer. With an api call i can dispatch the product to a customer. If product is in 'InStock' status, the api response is 200, if not the response is with statusCode 400. So my question is: How can i change the status of the product in the db for each test, so i can check each of the 3 statuses (if the api returns the proper response)? I know how to check the api response itself, but it's not clear to me how to change the status of the product in the db, before each test.


回答1:


Unlike @Maccurt, I would actually do it the way you propose (change the DB), so you can properly test e2e flow.

And instead of setting up test routes which would write to the DB you can use cy.task to talk to the Cypress Runner's node process which can write to the DB directly. It'd look like this:

Using postgres (node-postgres) in this example.

your-test.spec.js

describe("test", () => {
    it("test", () => {
        cy.task("query", {
            sql: `
                UPDATE product
                SET status = $1
                WHERE id = $2
            `,
            values: [ "InStock", 40 ]
        });

        // your cy assertions here
    });
});

cypress/plugins/index.js

const pg = require("pg");
const pool = /* initialize your database connection */;

module.exports = ( on ) => {

    on( "task", {
        query ({ sql, values }) {

            return pool.query( sql, values );
        }
    });
});



回答2:


You want to mock your api call so it responds with what you want. Cypress calls it stubbing. This will allow you to intercept your Rest call and replace it with what you want. You could also call an API to reset your DB, but I would not recommend that.

https://docs.cypress.io/guides/guides/network-requests.html#Requests

cy.server()           // enable response stubbing
cy.route({
  method: 'GET',      // Route all GET requests
  url: '/users/*',    // that have a URL that matches '/users/*'
  response: []        // and force the response to be: []
})


来源:https://stackoverflow.com/questions/54417335/how-to-change-property-of-a-record-in-db-with-cypress-io

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!