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: []
})