Is there any tip for unit testing with drizzle?
I'm trying to write unit test code with drizzle, but I have no idea how to write create statement with rollback.
- Using transaction for rollback could be a way, but I think it's too complicated for testing.
- Drizzle instance is too complicated to mock.
- I also have thought about creating repository class, but I don't think repository can handle complicated query (like query with join).
Can I get any advice?
16 Replies
Can you get a second database instance for testing with?
Test using a local version of your database. Going to be plenty of options out there.
I can, but I don't think that would help. I am running unit tests with my local DB, which is causing some values that should be unique (like user email) to be duplicated. I don't think either dropping tables or creating random value is an ideal solution too.
Do you keep data from other tests when running your unit tests? Why would it get duplicated?
The problem happened when running test multiple times. I was using sample email for testing, and running same test(inserting same value) made error.
I think you should always clear data between testing. Each test should have a "clean slate".
u can use
vitest --no-threads
and make sure you have a global beforeEach()
that runs truncate tables
--no-threads
ensures u only have 1 unit test running at a time, while it slows down the tests, but it ensures you have a real and clean-slate db to test against
in the case it's really slow as your test suites grow, just split up the tests into N machines on your CII know that is ideal, but clearing DB manually every time I fix some minor error or typo seems to be an overkill. Is there a way to clear DB automatically?
Shouldn't the tests be able to clear the database themselves?
I didn't know the could... Is that like running delete query in
beforeEach
?Not sure because I don't know how your tests are set up, but I would probably create a drop/seed script to run initially before each test.
Maybe I should've tried that first. Thank you for the help!
No problem, good luck
do you have example code to reference for doing this? I am able to create a docker container locally with code but not able to do much more afterwards, running into issues
Don’t clear the database after each test run and disable threading, I’ve done that before and that’s really slow
What I do is use random ids so that there’s no conflicts and have my tests run against an actual database
https://github.com/AnswerOverflow/AnswerOverflow/tree/main/packages/db
Here’s my project it’s open source so you can see how it all works
GitHub
AnswerOverflow/packages/db at main · AnswerOverflow/AnswerOverflow
Indexing Discord Help Channel Questions into Google - AnswerOverflow/AnswerOverflow