Professional Documents
Culture Documents
exFabrica · Follow
3 min read · Jun 8, 2022
Listen Share
Welcome back!
Our APIs work but we didn’t implement any tests to validate its behavior and
avoid possible regressions. If you remember, each time we used the CLI, NestJS
made for us all files to tests services, controllers and APIs (with E2E tests). So, we
are going to tests layer by layer and begin by unit tests on service layer.
The tests on service layer should focus on interactions with the TypeOrm
repository. So the first step is to mock the repository “InventoryItem”. NestJS has
the solution and proposes a function to do that. You have to import:
Since the goal is really to test the API calls, we have to set up new configuration
elements. Open a terminal and add the following library:
At the root of the solution, we add a NodeJS “.env” file. This is the entry point for
our NestJS configuration. Inside this file, we add 2 keys:
DATABASE_NAME_FOR_DEV = “sqlite”
DATABASE_NAME_FOR_TEST = “dbE2E”
Back to our E2E files (Test folder in each applications). A required action is
mandatory to continue, we need to update “jest-e2e.json” file and add a
“moduleNameMapper” section in the json to declare the shared library.
Once done, our tests will compile without error.
Notice that the creation of the test database and the insertion of data with a SQL
request: with this method, you add a full set of data to create a real test schema.
The database is created each time you launch the E2E tests.
request(app.getHttpServer()).get(‘/inventory’).
This asynchronous function allows us to query our test database, it returns the
HTTP response, so we can validate the data returned and finish our E2E tests.
For the “writer” the approach is the same but we will use POST, PUT and DELETE
to test the different parts of the API.
Mission complete!
Our tests are implemented ! We can think about the next part : DTO objects with
Automapper.
See U!
Nestjs Nodejs Api Development Javascript Development Typescript
Follow
Written by exFabrica
97 Followers
exFabrica
exFabrica
131 2
exFabrica
5
exFabrica
6 1
exFabrica
43 1
56
Daniel Delimata
11
Lists
How To Write Tests For Node Express Routes (With Auth Example)
A guide to writing comprehensive unit tests using Jest plus Typescript with examples
180 2
8
Enes Başpınar in Trendyol Tech
236