DEV Community

Discussion on: Need recommendations in Mocking database / Testing Cleanup (Unit Testing)

Collapse
isaacdlyman profile image
Isaac Lyman

I think what you're already doing is pretty much the way to go. You might want to be a little more specific about which user you're deleting, but that's the only change I would make.

If you want an example of an Express app that runs integration tests using a real database, here's one I've been working with:

github.com/isaaclyman/Edward-the-A...

This is the test utilities file, which is imported by most of the test suites.

Before every test, I run "deleteTestUser", which deletes all the content in the database that is foreign-keyed to the test user. Then I run "createTestUser", which re-creates the test user. And then I have utility methods for creating content for the test user.

I'm using Ava/supertest/Postgres/knex, so the tech is different, but the principle is the same.

One thing I recommend you keep doing is to do all test cleanup in the beforeEach section of the test suite. If you do it in afterEach and the test fails, the data won't be cleaned up, and your next test run will be polluted with old test data.