Writing Our First Test in Deno
Learn to write tests in a Deno application.
We'll cover the following
Before we start writing our test, it’s important to remember a few things. The most important of them is, why are we testing?
There might be multiple answers to this question, but most of them will gesture toward guaranteeing that the code is working. We might also say that utilizing them provides flexibility when it comes to refactoring or that valuing short feedback cycles during implementation is highly beneficial—we can agree with both of these perspectives. Since we didn’t write a test before implementing these features, the latter doesn’t apply too much to us.
We’ll keep these objectives in mind throughout this chapter. In this lesson, we’ll write our first test. We’ll use the application we wrote in the previous chapters and add tests to it. We’ll write two types of tests: integration and unit tests.
Integration tests will test how different components of the application interact. Unit tests test layers in isolation. If we think of it as a spectrum, unit tests are closer to the code, while integration tests are closer to the user. On the very end of the user side, there are also end-to-end tests. Those are the tests that test the application by emulating the user behavior, which we won’t cover in this chapter.
Parts of the patterns we used when developing the actual application, such as dependency injection and inversion of control, are of great use when it comes to testing. Since we developed our code by injecting all its dependencies, now, it’s just a matter of mocking those dependencies on tests. Remember: code that is easy to test is normally easy to maintain.
The first thing we’ll do is write tests for the business logic. Currently, since our API is quite simple, it doesn’t have much business logic. Most of it is living on UserController
since MuseumController
is very simple. We’ll start with the latter.
To write tests in Deno, we’ll need to use the following:
- The Deno test runner
- The
test
method from theDeno
namespace - The assertion methods from the Deno standard library
These are all part of Deno, distributed and maintained by the core team. There are many other libraries that can be used in tests that we can find in the community. We’ll use what’s provided by default in Deno since it works just fine and allows us to write clear and readable tests.
Let’s go and learn how we can define a test!
Create a free account to view this lesson.
By signing up, you agree to Educative's Terms of Service and Privacy Policy