javascripttestingsupertest

How to handle databases when testing with supertest?


I can't find a conclusive answer to this. I don't know if I should use the production DB and delete the test documents that were created when all tests are run, or if I should make a clone of the DB and use that for testing, to avoid any unwanted behavior.

For now, I've been using the production DB and what I do is put the tests in this order: POST, GET, PATCH, DELETE. This way the DELETE test gets rid of the document created during the previous test/s. This works fine generally, but I'm pretty sure it is not a good practice.


Solution

  • Your feeling that this is not a good practice is right IMHO. Testing on a productive system / database should never be the way to go. Here are some examples, what could happen:

    Cloning the productive DB, as you suggested, is one valid possibility, if the data contained isn't too sensitive. That keeps you as close as possible to the "reality" without endangering the productive data. Depending on the size of your production database, this might also be unnecessary expense. As your tests will probably need very little data, it is reasonable to deploy a test database containing only the data needed for your tests.

    If I got your question right, you're even creating the database contents yourself during your test (POST / INSERT), retrieving them (GET / SELECT), altering them (PATCH / UPDATE) and then deleting the afterwards (DELETE / DELETE). So even an empty database with just the bare tables could suffice.

    One last point: Depending on your setup, you might also not need to have the test database on the same DBMS (PostgreSQL / MariaDB / Oracle / ...) the production database is using. For test usage, you could just spin up some lightweight, transient database system like e. g. H2 or SQLite.