Cleardown test data using @badeball/cypress-cucumber-preprocessor

Viewed 47

I am new to Cucumber testing. I have a starter test which works ok, but I need to clear down the database in between tests.

This is the scenario:

Scenario: Should update the stock levels
 Given user is on the product page
 When user updates the stock quantity
 Then the new stock quantity is available on the product page

How do I handle cleardown for the the database in Cucumber? I've seen the recipe Seeding Your Database in Node but how do I implement that in Cucumber?

2 Answers

In your step file, you can just add a beforeEach() hook exactly as you would in a non-cucumber Cypress test.

import { Given, When, Then } from "@badeball/cypress-cucumber-preprocessor";

beforeEach(() => {
  // reset database
  cy.fixture('my-data.json').then(data => {
    cy.task('seed:db', data)
  })
})

Given('user is on the product page', () => {
  ...
})

You have a few places to call the task.

If using the Mocha beforeEach(), it will run first - ahead of the Cucumber methods.

You can also import Cucumber Before() which is a wrapper around the Mocha hook and runs after the beforeEach() call.

Or you could call the database seed task at the start of the Given() method.

import { When, Then, Before, Given } from "@badeball/cypress-cucumber-preprocessor";

beforeEach(() => {
  // reset database
  cy.fixture('dbdata.json').then(data => {
    cy.task('seed:db', data)
  })
})

Before(() => {
  // reset database
  cy.fixture('dbdata.json').then(data => {
    cy.task('seed:db', data)
  })
})

Given('user is on the product page', () => {
  // reset database
  cy.fixture('dbdata.json').then(data => {
    cy.task('seed:db', data)
  })
  cy.visit(...)
})
Related