Reputation: 227
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.
Upvotes: 3
Views: 13145
Reputation: 1128
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.
Upvotes: 10
Reputation: 18618
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
Upvotes: 0
Reputation: 1285
Depending on your needs, you could do one of the following:
afterEach
describe('Example', () => {
afterEach(() => {
// delete the record
})
// Include tests here
})
after:run
hook defined here: https://docs.cypress.io/api/plugins/after-run-apiUpvotes: 0