Introduction
On this article I will do some demonstration how to create a unit service for your Nest Js application, the talking points that will be covered are:
- Creating Testing Module
- Creating Test
- Testing Private and Static Method [TBD]
Testing
Creating a test will provide us a better perspective about code that we will / have created. There are 2 types of testing that we can create as a software engineer, e2e testing and unit testing.
E2E Testing
End-to-end testing is the type of software testing used to test entire software from starting to the end along with its integration with the external interfaces. The main purpose of end-to-end testing is to identify the system dependencies and to make sure that the data integrity and communication with other systems, interfaces and databases to exercise complete productions.
Unit Testing
Unit Testing is the type of software testing level in which each individual components of a software are tested separately. It is generally performed by developer. It can’t be used for those systems which have a lot of interdependence between different modules. It does not allow for parallel testing.
Creating Testing Module
Let say we have a service called BookService
that injected by BookRepositoryService
and we want to make a test for this BookService
service. As a notes, on by creating unit testing
we have to focus on what module / function that want to be tested, for the other module / function that we use on those module we want to test and come from the outside, must be mocked.
On our test file we mock '../../utils'
because we use it on BookService
.
we use beforeEach
hooks to create testingModule
so our BookService
service can be provide on this testing file. We create MockBookRepositoryService
that will be use to mock BookRepositoryService
. This MockBookRepositoryService
will contain the same method as BookRepositoryService
Creating Test
On line 7-12
and 18-20
we use spy
to 'spy' other method that we use on our BookService
so we can have our expectation for the kind of our behavior that we want for our tested method
, for instance this scenario bookService.createBook
method. On the line 13
, I have create other helpers
that only used for our test purpose. And the last part for creating test, we can call expect
to see the exact behavior that we want to be happened on our method / service.
Conclusion
Creating unit test would be pain in the a**, but as a software engineer, having a code that has been tested would make us more confident to set our service on production level. And by the time on my perspective, creating unit test will make us to be more critical while creating a method / service, and as far we know that, what we have been created must can be tested.
sources: