Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm new to cypress and I'm wondering how can I do the following checks: I have a case: I have a product in the DB, that can have statuses: InStock and OutOfStock and Discontinued. If a 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 a 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.

like image 754
user10983481 Avatar asked Jan 01 '23 08:01

user10983481


1 Answers

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);
        }
    });
});
like image 163
dwelle Avatar answered Jan 05 '23 17:01

dwelle