Test suites with Jasmine – Testing Angular (2024)

Angular ships with Jasmine, a JavaScript framework that enables you to write and execute unit and integration tests. Jasmine consists of three important parts:

  1. A library with classes and functions for constructing tests.
  2. A test execution engine.
  3. A reporting engine that outputs test results in different formats.

If you are new to Jasmine, it is recommended to read the official Jasmine tutorial. This guide provides a short introduction to Jasmine, exploring the basic structure and terminology that will be used throughout this guide.

Creating a test suite

In terms of Jasmine, a test consists of one or more suites. A suite is declared with a describe block:

describe('Suite description', () => { /* … */});

Each suite describes a piece of code, the code under test.

describe is a function that takes two parameters.

  1. A string with a human-readable name. Typically the name of the function or class under test. For example, describe('CounterComponent', /* … */) is the suite that tests the CounterComponent class.
  2. A function containing the suite definition.

A describe block groups related specs that we will learn about in the next chapter.

describe blocks can be nested to structure big suites and divide them into logical sections:

describe('Suite description', () => { describe('One aspect', () => { /* … */ }); describe('Another aspect', () => { /* … */ });});

Nested describe blocks add a human-readable description to a group of specs. They can also host their own setup and teardown logic.

Specifications

Each suit consists of one or more specifications, or short, specs. A spec is declared with an it block:

Again, it is a function that takes two parameters. The first parameter is a string with a human-readable description. The second parameter is a function containing the spec code.

The pronoun it refers to the code under test. it should be the subject of a human-readable sentence that asserts the behavior of the code under test. The spec code then proves this assertion. This style of writing specs originates from the concept of Behavior-Driven Development (BDD).

One goal of BDD is to describe software behavior in a natural language – in this case, English. Every stakeholder should be able to read the it sentences and understand how the code is supposed to behave. Team members without JavaScript knowledge should be able to add more requirements by forming it does something sentences.

Ask yourself, what does the code under test do? For example, in case of a CounterComponent, it increments the counter value. And it resets the counter to a specific value. So you could write:

it('increments the count', () => { /* … */});it('resets the count', () => { /* … */});

After it, typically a verb follows, like increments and resets in the example.

Some people prefer to write it('should increment the count', /* … */), but should bears no additional meaning. The nature of a spec is to state what the code under test should do. The word “should” is redundant and just makes the sentence longer. This guide recommends to simply state what the code does.

Structure of a test

Inside the it block lies the actual testing code. Irrespective of the testing framework, the testing code typically consists of three phases: Arrange, Act and Assert.

  1. Arrange is the preparation and setup phase. For example, the class under test is instantiated. Dependencies are set up. Spies and fakes are created.
  2. Act is the phase where interaction with the code under test happens. For example, a method is called or an HTML element in the DOM is clicked.
  3. Assert is the phase where the code behavior is checked and verified. For example, the actual output is compared to the expected output.

How could the structure of the spec it('resets the count', /* … */) for the CounterComponent look like?

  1. Arrange:

    • Create an instance of CounterComponent.
    • Render the Component into the document.
  2. Act:

    • Find and focus the reset input field.
    • Enter the text “5”.
    • Find and click the “Reset” button.
  3. Assert:

    • Expect that the displayed count now reads “5”.

This structure makes it easier to come up with a test and also to implement it. Ask yourself:

  • What is the necessary setup? Which dependencies do I need to provide? How do they behave? (Arrange)
  • What is the user input or API call that triggers the behavior I would like to test? (Act)
  • What is the expected behavior? How do I prove that the behavior is correct? (Assert)

In Behavior-Driven Development (BDD), the three phases of a test are fundamentally the same. But they are called Given, When and Then. These plain English words try to avoid technical jargon and pose a natural way to think of a test’s structure: “Given these conditions, when the user interacts with the application, then it behaves in a certain way.”

Expectations

In the Assert phase, the test compares the actual output or return value to the expected output or return value. If they are the same, the test passes. If they differ, the test fails.

Let us examine a simple contrived example, an add function:

const add = (a, b) => a + b;

A primitive test without any testing tools could look like this:

const expectedValue = 5;const actualValue = add(2, 3);if (expectedValue !== actualValue) { throw new Error( `Wrong return value: ${actualValue}. Expected: ${expectedValue}` );}

We could write that code in a Jasmine spec, but Jasmine allows us to create expectations in an easier and more concise manner: The expect function together with a matcher.

const expectedValue = 5;const actualValue = add(2, 3);expect(actualValue).toBe(expectedValue);

First, we pass the actual value to the expect function. It returns an expectation object with methods for checking the actual value. We would like to compare the actual value to the expected value, so we use the toBe matcher.

toBe is the simplest matcher that applies to all possible JavaScript values. Internally, it uses JavaScript’s strict equality operator ===. expect(actualValue)​.toBe(expectedValue) essentially runs actualValue === expectedValue.

toBe is useful to compare primitive values like strings, numbers and booleans. For objects, toBe matches only if the actual and the expected value are the very same object. toBe fails if two objects are not identical, even if they happen to have the same properties and values.

For checking the deep equality of two objects, Jasmine offers the toEqual matcher. This example illustrates the difference:

// Fails, the two objects are not identicalexpect({ name: 'Linda' }).toBe({ name: 'Linda' });// Passes, the two objects are not identical but deeply equalexpect({ name: 'Linda' }).toEqual({ name: 'Linda' });

Jasmine has numerous useful matchers built-in, toBe and toEqual being the most common. You can add custom matchers to hide a complex check behind a short name.

The pattern expect(actualValue).toEqual(expectedValue) originates from Behavior-Driven Development (BDD) again. The expect function call and the matcher methods form a human-readable sentence: “Expect the actual value to equal the expected value.” The goal is to write a specification that is as readable as a plain text but can be verified automatically.

Efficient test suites

When writing multiple specs in one suite, you quickly realize that the Arrange phase is similar or even identical across these specs. For example, when testing the CounterComponent, the Arrange phase always consists of creating a Component instance and rendering it into the document.

This setup is repeated over and over, so it should be defined once in a central place. You could write a setup function and call it at the beginning of each spec. But using Jasmine, you can declare code that is called before and after each spec, or before and after all specs.

For this purpose, Jasmine provides four functions: beforeEach, afterEach, beforeAll and afterAll. They are called inside of a describe block, just like it. They expect one parameter, a function that is called at the given stages.

describe('Suite description', () => { beforeAll(() => { console.log('Called before all specs are run'); }); afterAll(() => { console.log('Called after all specs are run'); }); beforeEach(() => { console.log('Called before each spec is run'); }); afterEach(() => { console.log('Called after each spec is run'); }); it('Spec 1', () => { console.log('Spec 1'); }); it('Spec 2', () => { console.log('Spec 2'); });});

This suite has two specs and defines shared setup and teardown code. The output is:

Called before all specs are runCalled before each spec is runSpec 1Called after each spec is runCalled before each spec is runSpec 2Called after each spec is runCalled after all specs are run

Most tests we are going to write will have a beforeEach block to host the Arrange code.

Faking dependencies

Test suites with Jasmine – Testing Angular (2024)

FAQs

Test suites with Jasmine – Testing Angular? ›

The Angular CLI downloads and installs everything you need to test an Angular application with Jasmine testing framework.

How to test Angular using Jasmine? ›

A Simple Test Example
  1. // A Jasmine suite describe('Adder', () => { });
  2. function add(first, second) { if (true) { // why? if (true) { // why?? if (1 === 1) { // why?!?1 return first + second; } } } }
  3. ng new angular-testing --routing.
  4. cd angular-testing ng serve -o.
  5. ng test.
  6. ng g component home.
Sep 21, 2020

Does Jasmine work with Angular? ›

The Angular CLI downloads and installs everything you need to test an Angular application with Jasmine testing framework.

What is test suite in Jasmine? ›

Jasmine is a testing framework for JavaScript. Suite is the basic building block of Jasmine framework. The collection of similar type test cases written for a specific file or function is known as one suite. It contains two other blocks, one is “Describe()” and another one is “It()”.

How an Angular component is tested using the Jasmine test framework? ›

To run your tests using the Angular CLI, you use the ng test command in your terminal. As a result, Karma will open up the default browser and run all the tests written with the aid of Jasmine and will display the outcome of those tests.

Does Angular use karma or Jasmine? ›

When creating Angular projects using the Angular CLI it defaults to creating and running unit tests using Jasmine and Karma. Whenever we create files using the CLI , as well as creating the main code file it also creates a simple Jasmine spec file named the same as the main code file but ending in . spec.

What is the difference between karma and Jasmine in Angular? ›

Jasmine is a JavaScript testing framework and Karma is a node-based testing tool for JavaScript codes across multiple real browsers. This blog helps you get started with Angular unit testing leveraging Karma and Jasmine.

Which automation tool is best for Angular applications? ›

Protractor. This open-source framework automates end-to-end testing primarily for Angular and AngularJS applications. It works as an integrator of Selenium, WebDriver, Jasmine, Node.

Should I use Jest or Jasmine? ›

For powerful UI-based applications, Jest is a good choice. For complex back-end applications, Mocha is a proper fit. Jasmine works better with light and simple projects. Built-in assertion libraries and auto-mocking features are available.

How to mock a pipe in Jasmine Angular? ›

A mock pipe in Angular tests can be created by MockPipe function. The second parameter of the function accepts a custom transform callback. The mock pipe has the identical interface as its source pipe, but all its methods are dummies.

What is the difference between test plan and test suite? ›

A test suite is a set of test cases which are logically connected. Eg: test cases which test the same functionality of an app. A test plan is plan how you want to execute your tests to reach your desired test coverage.

What is the difference between test set and test suite? ›

A test case is a set of instructions that outlines how to execute a specific test on a particular aspect of the software, while a test suite is simply a collection of multiple related tests. In other words, any software testing endeavor's pieces can be classified as test cases.

What is test case vs test suite? ›

A test case answers the question: What am I going to test? You develop test cases to define the things that you must validate to ensure that the system is working correctly and is built with a high level of quality. A test suite is a collection of test cases that are grouped for test execution purposes.

What type of testing is Jasmine? ›

Yes, Jasmine is a unit testing tool for JavaScript. It is a behavior-driven development (BDD) framework that provides a suite of matchers for making assertions about the code being tested. It does not require a DOM (Document Object Model) and has a clean, obvious syntax, so it's easy to write tests.

How does Jasmine testing work? ›

Jasmine follows Behavior Driven Development (BDD) procedure to ensure that each line of JavaScript statement is properly unit tested. By following BDD procedure, Jasmine provides a small syntax to test the smallest unit of the entire application instead of testing it as a whole.

How to generate test cases for Angular? ›

How to write a Unit Test in Angular?
  1. describe() – It's a suite of Test scripts that calls a global Jasmine function with two parameters: a string and a function. ...
  2. it() – It's the smallest unit test case that is written to be executed, which calls a global Jasmine function with two parameters: a string and a function.
Apr 21, 2023

How to test performance of Angular application? ›

The first step is to load your Angular app in a Chrome browser. And next get ready to trigger the performance problem you're experiencing. Then you'll want to open Chrome's developer tools and select the Performance tab. Click the record button when you're ready to start profiling the performance of your Angular app.

How to do unit testing in Angular using Karma Jasmine? ›

An environment to run angular tests is being created using all the imports at the beginning of the file. TestBed is a powerful unit testing tool provided by angular, and it is initialized in this file. Finally, karma loads all the test files of the application matching their names against a regular expression.

How do you check Angular is working or not? ›

Checking the Angular Version
  1. Open the Terminal + view in your project and type ng version . For recent versions of Angular, this will list the versions of several Angular packages that you have installed in your project. ...
  2. Open the package. json file and examine the Angular packages referenced in your project.

How to test Angular test cases? ›

How to write a Unit Test in Angular?
  1. describe() – It's a suite of Test scripts that calls a global Jasmine function with two parameters: a string and a function. ...
  2. it() – It's the smallest unit test case that is written to be executed, which calls a global Jasmine function with two parameters: a string and a function.
Apr 21, 2023

References

Top Articles
Latest Posts
Article information

Author: Dong Thiel

Last Updated:

Views: 6503

Rating: 4.9 / 5 (79 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Dong Thiel

Birthday: 2001-07-14

Address: 2865 Kasha Unions, West Corrinne, AK 05708-1071

Phone: +3512198379449

Job: Design Planner

Hobby: Graffiti, Foreign language learning, Gambling, Metalworking, Rowing, Sculling, Sewing

Introduction: My name is Dong Thiel, I am a brainy, happy, tasty, lively, splendid, talented, cooperative person who loves writing and wants to share my knowledge and understanding with you.