I have just created a test file (MERN stack) on cypress, and after I run the test, I want to delete it from my Mongoose database. Are there any ways that I can delete that data right after the test runs successfully? I don't want to do it manually.
3 Answers
Cypress recommends not to use after()
or afterEach()
to do cleanup, but instead to use before()
or beforeEach()
to clean DB prior to seeding or testing
Best Practice: Clean up state before tests run.
Reason is, if there is a crash or a programmed test retry, the after*
hooks may not be run.
Doing it before*
means the test always sees the correct DB state.

- 928
- 1
- 7
-
4If this is a formal recommendation, could you please [edit] your answer to add a link to the relevant documentation. – David Buck Sep 09 '21 at 05:21
-
7[Best Practices - Using after or afterEach hooks](https://docs.cypress.io/guides/references/best-practices#Using-after-or-afterEach-hooks). It's more anecdotal than formal. – user16695029 Sep 09 '21 at 07:18
One way that I use is to create a separate spec file(eg.cleanup.spec.js) with all your cleanup scripts and make sure that this file is run at the end of the test. To make sure of that, you can use the testFiles
option in the cypress.json
. What this does is it loads the tests in a sequence that you have mentioned.
"testFiles": [
"Some Test 1.spec.js",
"Some Test 2.spec.js",
"Some Test 3.spec.js",
"cleanup.spec.js"
]
Using afterEach()
to remove test data has always caused issues in the past for me for reasons as mentioned by @Mihi

- 17,144
- 3
- 29
- 52
-
Please see @Brendan caveat [here](https://stackoverflow.com/a/59690611/16695029) – Michael Hines Sep 10 '21 at 03:11
-
1Also some advice from Gleb against test ordering [here](https://github.com/cypress-io/cypress/issues/390#issuecomment-404491057) (just to balance the discussion - if it works then ok) – Michael Hines Sep 10 '21 at 03:17
Depending on your needs, you could do one of the following:
- Delete the record using
afterEach
describe('Example', () => {
afterEach(() => {
// delete the record
})
// Include tests here
})
- Use the
after:run
hook defined here: https://docs.cypress.io/api/plugins/after-run-api

- 1,240
- 9
- 13