Unit Testing an Angular Custom Services

Unit Testing an Angular Services

In this article, we shall be learning how to Unit Test and Mock Angular Custom Services.

We shall be using Angular Unit Testing Best Practices which we learned in our last article. Please see below as references.

Please see here GitHub link for complete example,

GitHub: https://github.com/thecodebuzz/angular-8-getting-started-ivy

Getting started

Below is a sample MessageService defined @Injectable Decorator.

  • Please open the message.service.ts.
  • We will write unit tests for this service particularly.

Unit Testing an Angular Services

  • Please create a new spec file message.service.spec.ts and paste in the below code.
  • So here we are creating Instance MessageService class and calling its services.
  • As you can see, this is not different from the Component or other regular testing.

import { MessageService } from "./message.service";
describe('Message Service', ()=>{
   let service : MessageService;
   it('should have no messages to start',()=>{
       //Arrange
       service = new MessageService();
       //Act
       let val = service.messages.length;
       //Assert
       expect(val).toBe(0);
   })
   it('should add a message on calling add',()=>{
       //Arrange
       service = new MessageService();
       service.add('newMessage');
       //Act
       let val = service.messages.length;
       //Assert
       expect(val).toBe(1);
   })
   it('should remove all messages when clear is called',()=>{
       //Arrange
       service = new MessageService();
       service.add('newMessage');
       //Act
       service.clear();
       //Assert
       expect(service.messages.length).toBe(0);
   })
})

  • Again, we can used our regular AAA pattern to write our unit tests.
  • I’ll save these tests, we’ll head over to Karma, and it’s picked up the new tests and it’s green.

Unit Testing an Angular Services

Using the above concepts one can test any other Service components in Angular projects. Please see below article in how to unit test Angular HttpClient services in Angular,

Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



Leave a Reply

Your email address will not be published. Required fields are marked *