I am looking to write unit and/or integration tests for one of the projects that I work on. I connect to mongo and postgres(using plain drivers, no ORM frameworks on top like mongoose or knex). I use express for web services.
I don't use any kind of ORM
So, now that I have my stack explained, I would like some suggestions on how to implement the unit tests.
I have written unit & integration tests in java quite some time back but I have no experience for the same in node.js. I used to have a mock data feed which is used to mimic the database. It uses the h2
database(an in memory database which is created along with tests and dies after the test cycle, magically!!).
Now, I am not sure if I can do something similar in node.js. I do want to have an approach like this because, I write my own raw sql queries. Right now, there is no plan to move it to an ORM as we have lot of custom logic that happens inside. So, is there a way or someone has implemented something similar in typescript?
Suggestions Requested
Top comments (7)
This is one of those things where there is no general consensus on the "correct way". Some people will say to stub the database calls (i.e. - your query functions), some will say to use a test database and rollback the transaction after each test runs, some will say to use a set of fixtures to prepopulate the database, some will say to use factory functions to insert records rather than use fixtures... I think you get my point...
The way I'm currently doing it (which could change, but it works for me for now) - is using a test database with a set of fixtures/seed data. I use docker-compose which makes it easy to spin up test databases using the same Docker images/configurations as you'd use in production. So my database layer unit tests talk to a real database. IMO it's best that this database be a real one and not an in-memory database. You want your DAL tests to mimic what will be run in production as closely as possible. If you're concerned that using a real database will slow your tests down, check out this article which has good recommendations for speeding that up significantly: pythonspeed.com/articles/faster-db...
Thanks a lot. That's what I was looking for
I use Mocha and Chai and target a separate test database, and run a cleanup script in the
after()
hook.If you'd like a more convenient access layer for Postgres but still want it to be easy to run raw SQL, you might be interested in (my project) MassiveJS.
I'll check it out for sure thanks
I don't understand your question. Your title says you want to test your ORM, but you say you don't have an ORM, and don't plan to add one. Can you explain more clearly what you're asking?
I think I was not very clear. I wanted to test my custom ORM layer. I actually meant to say that I donot use any ORM frameworks, but I write my own queries. I have edited the question also.Hope it's clear now.
Checkout if this package helps
npmjs.com/package/sql-unittest