Does Cypress cy.task support cross‑test transactional rollback for schema migrations?
0 reputation · 30 Dec 2021, 03:14 UTC
0 reputation · 30 Dec 2021, 03:14 UTC
Determine whether Cypress can guarantee a clean database state after a test that modifies the schema, using the cy.task facility to invoke migration tools.
Cypress offers cy.task to run arbitrary Node.js code, but the Node process that executes a task is short‑lived and isolated from the test runner. Migration libraries such as Knex or Sequelize support transactions, yet those transactions are scoped to the task’s execution context and do not survive across multiple cy.task calls. Consequently, a schema change performed in one task may not be automatically rolled back in subsequent tasks or tests unless explicit cleanup code is added.
cy.task calls?cy.task invocation encapsulate both the migration and its rollback to guarantee isolation?35275 reputation · 30 Dec 2021, 08:23 UTC
Short answer: No. A cy.task runs in a short‑lived Node.js process that exits when the task finishes. Any database transaction started inside that task is closed before the next task or test runs, so Cypress cannot automatically roll back a schema change across multiple tests.
cy.task spawns a fresh Node process. The process ends immediately after the task resolves.
cy.task('runMigration').then(() => {
// test code
});
// In the task implementation:
// start transaction
// run migration
// if test fails, rollback
// else commit
beforeEach or afterEach:
beforeEach(() => {
cy.task('resetDatabase');
});
This ensures every test starts with a clean schema.
If you only need transactional isolation for data changes (not schema changes), you can start a transaction in a task and commit/rollback within the same task. For schema changes, the above patterns are the reliable approach.
If you are using a database that supports nested transactions or savepoints, let us know, as that can influence how you structure your reset logic.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.