Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Right now I’m trying to unit test an API on node that does a database query.

I’m using express, mocha, supertest and typeorm.

Mocking the database is fucking black magic. So I gave up and simply use an in memory SQLite db and add some records in the test body for my API to fetch and return so I can test.

I’d like the db to basically get nuked and recreated after every test.

So I use “afterEach” to close the connection and create a new one.

No matter what I do, when I call the api endpoint using supertest it tells me my DB connection is closed.

You’re thinking maybe the previous test didn’t reopen it or something. But there only one test.

It’s like it’s closing it _before_ the test runs. As if afterEach is not waiting on the result from supertest (yes I awaited).

I spent a _whole day_ today trying to understand just what the fuck is going on.

Gimme goroutines _any day_.



Testing with the database has to be one of the things I love the most about Ecto. No need to mock anything, no need to have special branching logic for test versus prod. Just use the database like you normally do. It gives you a degree of confidence that is on another level. Check out https://hexdocs.pm/ecto_sql/Ecto.Adapters.SQL.Sandbox.html for more info!


Testing with the database isn't particularly efficient. If you have enough tests, it becomes worth it to mock whatever would touch the database just so the tests pass in a reasonable amount of time.


> Testing with the database isn't particularly efficient.

Anecdata, but my experience with Ecto sandbox + thousands of tests says otherwise. Mocking would be faster? Probably. But IMO not worth the effort, given it's already fast enough.

To be fair, I have worked with Elixir codebases that generated humongous amount of data per-test, only to test a fraction of this data. This kind of test was slow, but it would be much more efficient to generate only the data you actually need.


> But IMO not worth the effort, given it's already fast enough.

Not only that, but if you're testing with the database, you get to test your queries. That seems worth it being a bit slower.


Maybe not relevant to your issue, but sqlite in-memory databases can be tricky. IIRC closing the connection wipes it out. Creating a new connection means creating a new fresh database.

Tried it on-disk?




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: