Angular Unit Testing and Mocking Pipes

In this article, we shall be Unit Testing and Mocking Pipes in Angular Application.

We shall be using angular unit-testing best practices which we learned in our last article,

Here we are making use of same Tour of Heroes sample

  • Open the file strength.pipe.ts.
  • We are going to start by testing this StrengthPipe.

  • To create a test for this we’ll create a new file, and we’re going to create it right alongside that StrengthPipe, and we’ll call this strength.pipe.spec.ts.
  • Paste the below code in strength.pipe.spec.ts:
  • We start with our describe. We’re going to name this after our class, which is StrengthPipe, and then our callback function, and within here we can write our first test.
  • Our first test is going to be that ‘it should display weak if the strength is 3’. 
  • We will use the AAA pattern:
import { StrengthPipe } from "./strength.pipe";
describe('Strength Pipe', () => {
   it('should display weak if strength is 3', () => {
       //Arrange
       let pipe = new StrengthPipe();
       //Act
       let val = pipe.transform(3);
       //Assert
       expect(val).toEqual('3 (weak)');
   })
})

Running the Unit Test:

Paste the below command in the terminal to run the unit test:

ng test

  • Karma will run the test for us. And if we head over to the browser that Karma’s running, we can see that it’s picked up that StrengthPipe test, it’s executed it, and we’re getting a green that we’re passing this test. 
  • We can write a similar test for the other value like below.

it('should display strong if strength is 12', () => {
       //Arrange
       let pipe = new StrengthPipe();
       //Act
       let val = pipe.transform(12);
       //Assert
       expect(val).toEqual('12 (strong)');
   })
  • We can see both the tests are passing.
blank

References



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 *