Make things testable
Something that I keep hearing is “testing is too hard!”. And, yes, I agree. Testing is not a trivial thing. But it is not that hard! Testing can get significantly harder if your application is not testable. People keep asking me: “how can I test my application?”. But, what they should be asking is: “how can I make my application testable?”. But what do I mean by “testable”? Tests consist of three simple parts: Arrange, act and assert....
Node.js testing - Mocking
In the last part of this series, we were introduced to the concept of mocking. It turns out that we can also mock javascript functions as we are going to see. Let’s say that we have function A that happens to call function B but we don’t want to actually call function B while testing A. How can we get around this? Mocking is the answer! Let’s say we have the following situation:...
Node.js testing - Third-party services
Often we need to test a piece of code that make requests to a third-party service. In that case, we don’t want to rely on a third-party service being online to run our tests. Even if the third-party service is online, we still don’t want to depend on it because our internet connection may be slow or the service may be not fast enough for testing purposes. Also, we always want our tests to run as fast as possible, so we don’t discourage our developers to run the tests constantly....
Node.js testing - Database
Sometimes, the code that we want to test reads or writes to a database. In that case, we need a little more setup to be able to test the integration with our database. Let’s pretend we have an endpoint that creates pets: src/createApp.js: app.post('/pets', async (req, res) => { const pet = await pool.query( 'insert into pets (name) values ($1) returning *', [req.body.name] ) res.send(pet) }) Firstly, we need to connect to the DB and create our pets table:...
Node.js testing - Intro
All my colleagues know that I love testing. I really think that tests are a neat tool that can leverage our productivity and the quality of what we write. That being said, in this series of articles, we will be seeing how we can test everyday stuff like API endpoints, integration with databases, and third-party services. In this first part, we are going to see how to test express endpoints, come with me....