Unit Testing Angular 9 Application with Jasmine and Karma

Unit Testing Angular 9 Application with Jasmine and Karma

Unit Testing Angular 9 Application with Jasmine and Karma. We will learn how to write unit tests in for services and component in an Angular app using the Jasmine framework and Karma (JavaScript Test Runner). What types of tests? What is unit testing? How to unit test an Angular component? How to test an Angular application from scratch? How to unit test an Angular Service with HttpClient and HttpTestingController?

Angular 9 Unit Testing tutorial with an example. We will learn how to write unit tests in for services and component in an Angular app using the Jasmine framework and karma (JavaScript Test Runner).

We always ship our final product after making thorough testing, It is a fundamental step in software development, and it can be done via various testing methods.

There are many methods to test our code, such as automated testing, manual testing, performance testing, automated unit testing. These testing methods are chosen as per the testing requirement of an application.

There are 3 types of tests:

  • Unit tests
  • Integration tests
  • End-to-End (e2e) tests

In this tutorial, we will focus on unit testing with Jasmine and Karma.

Table of Contents

  • Angular 9 Unit Testing Example
  • Karma in Angular 8/9
  • Configure Development Environment
  • Setting Up Angular App
  • Angular Component Testing Example
  • Unit Testing with Angular Service with HttpClient & HttpTestingController API
  • Conclusion
Angular 9 Unit Testing Example

A unit test is the process of examining the specific part of the application and make sure it is working correctly and most importantly unit tests are written by developers.

Jasmine is an open-source behavior-driven testing framework crafted by Pivotal Labs. It is installed via Angular CLI and offers the hassle-free testing experience to test an Angular and JavaScript code.

Jasmine provides several valuable functions to write tests. Here are the main Jasmine methods:

  • it(): Declaration of a particular test
  • describe(): It’s a suite of tests
  • expect(): Expect some value in true form

Writing tests with Jasmine and Karma is very easy, so, we will create a basic Angular application, then create a simple Angular component and service. Then, we will write some test cases for Angular component, and also write unit test a service with HttpTestingController.

Let’s get started testing an Angular component with the Jasmine test framework.

Karma in Angular 8/9

Karma is a test runner tool, it creates a browser instance, run tests to provide the expected results.

The benefit of using Karma is that it can be operated via command line and It refreshes the browser automatically whenever we make even minor changes in our app.

Configure Development Environment

To get along with this tutorial you must have Node js and npm configured on your system. Skip this step, If you have already configured otherwise follow the below tutorial to set up Node and NPM on your device.

Downloading and installing Node.js and npm

Also, you must have installed the latest version of Angular CLI on your system.

npm install -g @angular/[email protected]

If Node, NPM, and Angular CLI configured adequately, then go to the next step.

Setting Up Angular App

Next, install the Angular project by running the below command:

ng new ng-unit-test

Head over to the project folder by using the following command:

cd ng-unit-test

Start the app on the browser:

ng serve --open

Now, you can view your app on the browser on the following port: localhost:4200.

Angular Component Testing Example

An Angular component is a collection of HTML template and a TypeScript class. So, to test a component first, we need to create a component.

Let’s name it pizza and run the below command to create the component.

ng generate component pizza

Above command has created a pizza folder, and inside the pizza folder create a title variable and assign some value to it.

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-pizza',
  templateUrl: './pizza.component.html',
  styleUrls: ['./pizza.component.css']
})

export class PizzaComponent implements OnInit {

  title = "I love pizza!"

  constructor() { }

  ngOnInit() {
  }

}

You can see there is another file created pizza.component.spec.ts and this is a test file which is responsible for testing in Angular and testing file looks like this.

import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { PizzaComponent } from './pizza.component';

describe('PizzaComponent', () => {
  let component: PizzaComponent;
  let fixture: ComponentFixture<PizzaComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ PizzaComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(PizzaComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

Writing tests in Angular is easy, now we are going to write a simple test within the describe() function.

it(`should have a title 'I love pizza!'`, async(() => {
  fixture = TestBed.createComponent(PizzaComponent);
  component = fixture.debugElement.componentInstance;
  expect(component.title).toEqual('I love pizza!');
}));

You need to use the ng test command to start testing an Angular component.

ng test

Above command built the app in watch mode and launched the karma.

The ng test command opened the watch mode in karma.

We added some content in the pizza component. Then we created the pizza component instance to verify its properties and functions inside of it for testing purpose.

Now, as you can see in the screenshot 5 specs and 0 failures, this means we passed the test for pizza as well as for AppComponent’s properties.

The fixture creates a wrapper around a component instance, The fixture TestBed.createComponent() method allows accessing the component and its template.

Unit Testing with Angular Service with HttpClient & HttpTestingController API

Next, we are going to look at how to unit test a service that handles the http requests in Angular.

Run the following command to create service inside the shared folder:

ng g s shared/post

We are using free REST API from JSONPlaceholder, a big thanks to them for providing such a beautiful collection of REST APIs.

After running the above command, we have got the following files:

app/shared/post.service.spec.ts

app/shared/post.service.ts

Next, import and register the PostService in app.module.ts file, also import and register HttpClientModule in the main app module file.

// app.module.ts

import { PostService } from './shared/post.service';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [...],
  imports: [
    HttpClientModule
  ],
  providers: [PostService],
  bootstrap: [...]
})

export class AppModule { }

Add the following code in the post.service.ts file, api is called and returns an Observable in the form of posts list. The JSONPlaceholder API returns an Observable and we are subscribing to it to get the posts data.

// shared/post.service.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';

export interface Post {
  userId: number;
  id: number;
  title: string;
  body: string;
}

@Injectable({
  providedIn: 'root'
})

export class PostService {
  REST_API: string = 'https://jsonplaceholder.typicode.com/posts';

  constructor(private http: HttpClient) { }

  getPosts(): Observable<Post[]> {
    return this.http.get<Post[]>(`${this.REST_API}`)
  }
}

HttpTestingController service are beneficial in mocking the HTTP requests, and this process can not be followed without taking the help of HttpClientTestingModule.

In this Angular 9 tutorial, we are going to write a unit test for mocking the HTTP GET request by taking the help of the HttpTestingController service.

Add the following code in the shared/post.service.spec.ts file.

import { TestBed, async, inject } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { PostService } from './post.service';

describe('PostService', () => {
  let postService: PostService;
  let httpMock: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        HttpClientTestingModule,
      ],
      providers: [
        PostService
      ],
    });

    postService = TestBed.get(PostService);
    httpMock = TestBed.get(HttpTestingController);
  });

  it(`should fetch posts as an Observable`, async(inject([HttpTestingController, PostService],
    (httpClient: HttpTestingController, postService: PostService) => {

      const postItem = [
        {
          "userId": 1,
          "id": 1,
          "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
          "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
        },
        {
          "userId": 1,
          "id": 2,
          "title": "qui est esse",
          "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
        },
        {
          "userId": 1,
          "id": 3,
          "title": "ea molestias quasi exercitationem repellat qui ipsa sit aut",
          "body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"
        }
      ];

      postService.getPosts()
        .subscribe((posts: any) => {
          expect(posts.length).toBe(3);
        });

      let req = httpMock.expectOne('https://jsonplaceholder.typicode.com/posts');
      expect(req.request.method).toBe("GET");

      req.flush(postItem);
      httpMock.verify();

    })));
});

Conclusion

Finally, Unit Testing Angular 9 Application with Jasmine & Karma tutorial with example is over. In this tutorial, we covered the following topics:

  • What types of tests?
  • What is unit testing?
  • How to unit test an Angular component?
  • How to test an Angular application from scratch?
  • How to unit test an Angular Service with HttpClient and HttpTestingController?

You can get the complete code of this tutorial on this Github repository.

JavaScript Testing - Unit Tests, Integration Tests & e2e Tests

JavaScript Testing - Unit Tests, Integration Tests & e2e Tests

JavaScript testing - i.e. unit tests, integration tests and e2e (UI) tests - can be intimidating. It shouldn't be! This video guides you through all the basics (including the "Why"?) of JavaScript testing. JavaScript Testing Introduction Tutorial - Unit Tests, Integration Tests & e2e Tests. Master JavaScript testing now!

JavaScript testing - i.e. unit tests, integration tests and e2e (UI) tests - can be intimidating. It shouldn't be! This video guides you through all the basics (including the "Why"?) of JavaScript testing. Master JavaScript testing now!

Unit Testing in JavaScript and Jasmine

Unit Testing in JavaScript and Jasmine

Learn how to unit test your JavaScript using the jasmine framework, from your first test to continuous integration. Jasmine is one of the popular JavaScript unit testing frameworks which is capable of testing synchronous and asynchronous JavaScript code. Unit Testing in JavaScript and Jasmine. Jasmine Unit Test Tutorial

Unit Testing in JavaScript and Jasmine | TLDR Jasmine Unit Test Tutorial By: Dylan Israel

Jasmine is one of the popular JavaScript unit testing frameworks which is capable of testing synchronous and asynchronous JavaScript code

An Introduction to Unit Testing in Angular

An Introduction to Unit Testing in Angular

Unit testing, as the name implies, is about testing individual units of code. Unit tests try to answer questions such as "Did I think about the logic correctly?" or "Does the sort function order the list in the right order

JavaScript is a dynamically typed language which comes with great power of expression, but it also comes with almost no help from the compiler. For this reason we feel very strongly that any code written in JavaScript needs to come with a strong set of tests. We have built many features into AngularJS which make testing your AngularJS applications easy. With AngularJS, there is no excuse for not testing.

Separation of Concerns

Unit testing, as the name implies, is about testing individual units of code. Unit tests try to answer questions such as "Did I think about the logic correctly?" or "Does the sort function order the list in the right order?"

In order to answer such a question it is very important that we can isolate the unit of code under test. That is because when we are testing the sort function we don't want to be forced into creating related pieces such as the DOM elements, or making any XHR calls to fetch the data to sort.

While this may seem obvious it can be very difficult to call an individual function on a typical project. The reason is that the developers often mix concerns resulting in a piece of code which does everything. It makes an XHR request, it sorts the response data, and then it manipulates the DOM.

With AngularJS, we try to make it easy for you to do the right thing. For your XHR requests, we provide dependency injection, so your requests can be simulated. For the DOM, we abstract it, so you can test your model without having to manipulate the DOM directly. Your tests can then assert that the data has been sorted without having to create or look at the state of the DOM or to wait for any XHR requests to return data. The individual sort function can be tested in isolation.

With great power comes great responsibility

AngularJS is written with testability in mind, but it still requires that you do the right thing. We tried to make the right thing easy, but if you ignore these guidelines you may end up with an untestable application.

Dependency Injection

AngularJS comes with dependency injection built-in, which makes testing components much easier, because you can pass in a component's dependencies and stub or mock them as you wish.

Components that have their dependencies injected allow them to be easily mocked on a test by test basis, without having to mess with any global variables that could inadvertently affect another test.

Additional tools for testing AngularJS applications

For testing AngularJS applications there are certain tools that you should use that will make testing much easier to set up and run.

Karma

Karma is a JavaScript command line tool that can be used to spawn a web server which loads your application's source code and executes your tests. You can configure Karma to run against a number of browsers, which is useful for being confident that your application works on all browsers you need to support. Karma is executed on the command line and will display the results of your tests on the command line once they have run in the browser.

Karma is a NodeJS application, and should be installed through npm/yarn. Full installation instructions are available on the Karma website.

Jasmine

Jasmine is a behavior driven development framework for JavaScript that has become the most popular choice for testing AngularJS applications. Jasmine provides functions to help with structuring your tests and also making assertions. As your tests grow, keeping them well structured and documented is vital, and Jasmine helps achieve this.

In Jasmine we use the describe function to group our tests together:

describe("sorting the list of users", function() {
  // individual tests go here
});

And then each individual test is defined within a call to the it function:

describe('sorting the list of users', function() {
  it('sorts in descending order by default', function() {
    // your test assertion goes here
  });
});

Grouping related tests within describe blocks and describing each individual test within an it call keeps your tests self documenting.

Finally, Jasmine provides matchers which let you make assertions:

describe('sorting the list of users', function() {
  it('sorts in descending order by default', function() {
    var users = ['jack', 'igor', 'jeff'];
    var sorted = sortUsers(users);
    expect(sorted).toEqual(['jeff', 'jack', 'igor']);
  });
});

Jasmine comes with a number of matchers that help you make a variety of assertions. You should read the Jasmine documentation to see what they are. To use Jasmine with Karma, we use the karma-jasmine test runner.

angular-mocks

AngularJS also provides the ngMock module, which provides mocking for your tests. This is used to inject and mock AngularJS services within unit tests. In addition, it is able to extend other modules so they are synchronous. Having tests synchronous keeps them much cleaner and easier to work with. One of the most useful parts of ngMock is $httpBackend, which lets us mock XHR requests in tests, and return sample data instead.

Testing a Controller

Because AngularJS separates logic from the view layer, it keeps controllers easy to test. Let's take a look at how we might test the controller below, which provides $scope.grade, which sets a property on the scope based on the length of the password.

angular.module('app', [])
.controller('PasswordController', function PasswordController($scope) {
  $scope.password = '';
  $scope.grade = function() {
    var size = $scope.password.length;
    if (size > 8) {
      $scope.strength = 'strong';
    } else if (size > 3) {
      $scope.strength = 'medium';
    } else {
      $scope.strength = 'weak';
    }
  };
});

Because controllers are not available on the global scope, we need to use angular.mock.inject to inject our controller first. The first step is to use the module function, which is provided by angular-mocks. This loads in the module it's given, so it is available in your tests. We pass this into beforeEach, which is a function Jasmine provides that lets us run code before each test. Then we can use inject to access $controller, the service that is responsible for instantiating controllers.

describe('PasswordController', function() {
  beforeEach(module('app'));

  var $controller, $rootScope;

  beforeEach(inject(function(_$controller_, _$rootScope_){
    // The injector unwraps the underscores (_) from around the parameter names when matching
    $controller = _$controller_;
    $rootScope = _$rootScope_;
  }));

  describe('$scope.grade', function() {
    it('sets the strength to "strong" if the password length is >8 chars', function() {
      var $scope = $rootScope.$new();
      var controller = $controller('PasswordController', { $scope: $scope });
      $scope.password = 'longerthaneightchars';
      $scope.grade();
      expect($scope.strength).toEqual('strong');
    });
  });
});

Notice how by nesting the describe calls and being descriptive when calling them with strings, the test is very clear. It documents exactly what it is testing, and at a glance you can quickly see what is happening. Now let's add the test for when the password is less than three characters, which should see $scope.strength set to "weak":

describe('PasswordController', function() {
  beforeEach(module('app'));

  var $controller;

  beforeEach(inject(function(_$controller_){
    // The injector unwraps the underscores (_) from around the parameter names when matching
    $controller = _$controller_;
  }));

  describe('$scope.grade', function() {
    it('sets the strength to "strong" if the password length is >8 chars', function() {
      var $scope = {};
      var controller = $controller('PasswordController', { $scope: $scope });
      $scope.password = 'longerthaneightchars';
      $scope.grade();
      expect($scope.strength).toEqual('strong');
    });

    it('sets the strength to "weak" if the password length <3 chars', function() {
      var $scope = {};
      var controller = $controller('PasswordController', { $scope: $scope });
      $scope.password = 'a';
      $scope.grade();
      expect($scope.strength).toEqual('weak');
    });
  });
});

Now we have two tests, but notice the duplication between the tests. Both have to create the $scope variable and create the controller. As we add new tests, this duplication is only going to get worse. Thankfully, Jasmine provides beforeEach, which lets us run a function before each individual test. Let's see how that would tidy up our tests:

describe('PasswordController', function() {
  beforeEach(module('app'));

  var $controller;

  beforeEach(inject(function(_$controller_){
    // The injector unwraps the underscores (_) from around the parameter names when matching
    $controller = _$controller_;
  }));

  describe('$scope.grade', function() {
    var $scope, controller;

    beforeEach(function() {
      $scope = {};
      controller = $controller('PasswordController', { $scope: $scope });
    });

    it('sets the strength to "strong" if the password length is >8 chars', function() {
      $scope.password = 'longerthaneightchars';
      $scope.grade();
      expect($scope.strength).toEqual('strong');
    });

    it('sets the strength to "weak" if the password length <3 chars', function() {
      $scope.password = 'a';
      $scope.grade();
      expect($scope.strength).toEqual('weak');
    });
  });
});

We've moved the duplication out and into the beforeEach block. Each individual test now only contains the code specific to that test, and not code that is general across all tests. As you expand your tests, keep an eye out for locations where you can use beforeEach to tidy up tests. beforeEach isn't the only function of this sort that Jasmine provides, and the documentation lists the others.

Testing Filters

Filters are functions which transform the data into a user readable format. They are important because they remove the formatting responsibility from the application logic, further simplifying the application logic.

myModule.filter('length', function() {
  return function(text) {
    return ('' + (text || '')).length;
  }
});

describe('length filter', function() {

  var $filter;

  beforeEach(inject(function(_$filter_){
    $filter = _$filter_;
  }));

  it('returns 0 when given null', function() {
    var length = $filter('length');
    expect(length(null)).toEqual(0);
  });

  it('returns the correct value when given a string of chars', function() {
    var length = $filter('length');
    expect(length('abc')).toEqual(3);
  });
});

Testing Directives

Directives in AngularJS are responsible for encapsulating complex functionality within custom HTML tags, attributes, classes or comments. Unit tests are very important for directives because the components you create with directives may be used throughout your application and in many different contexts.

Simple HTML Element Directive

Let's start with an AngularJS app with no dependencies.

var app = angular.module('myApp', []);

Now we can add a directive to our app.

app.directive('aGreatEye', function () {
    return {
        restrict: 'E',
        replace: true,
        template: '<h1>lidless, wreathed in flame, {{1 + 1}} times</h1>'
    };
});

This directive is used as a tag <a-great-eye></a-great-eye>. It replaces the entire tag with the template <h1>lidless, wreathed in flame, {{1 + 1}} times</h1>. Now we are going to write a jasmine unit test to verify this functionality. Note that the expression {{1 + 1}} times will also be evaluated in the rendered content.

describe('Unit testing great quotes', function() {
  var $compile,
      $rootScope;

  // Load the myApp module, which contains the directive
  beforeEach(module('myApp'));

  // Store references to $rootScope and $compile
  // so they are available to all tests in this describe block
  beforeEach(inject(function(_$compile_, _$rootScope_){
    // The injector unwraps the underscores (_) from around the parameter names when matching
    $compile = _$compile_;
    $rootScope = _$rootScope_;
  }));

  it('Replaces the element with the appropriate content', function() {
    // Compile a piece of HTML containing the directive
    var element = $compile("<a-great-eye></a-great-eye>")($rootScope);
    // fire all the watches, so the scope expression {{1 + 1}} will be evaluated
    $rootScope.$digest();
    // Check that the compiled element contains the templated content
    expect(element.html()).toContain("lidless, wreathed in flame, 2 times");
  });
});

We inject the $compile service and $rootScope before each jasmine test. The $compile service is used to render the aGreatEye directive. After rendering the directive we ensure that the directive has replaced the content and "lidless, wreathed in flame, 2 times" is present.

Underscore notation: The use of the underscore notation (e.g.: _$rootScope_) is a convention wide spread in AngularJS community to keep the variable names clean in your tests. That's why the $injector strips out the leading and the trailing underscores when matching the parameters. The underscore rule applies only if the name starts and ends with exactly one underscore, otherwise no replacing happens.

Testing Transclusion Directives

Directives that use transclusion are treated specially by the compiler. Before their compile function is called, the contents of the directive's element are removed from the element and provided via a transclusion function. The directive's template is then appended to the directive's element, to which it can then insert the transcluded content into its template.

Before compilation:

<div transclude-directive>
  Some transcluded content
</div>

After transclusion extraction:

<div transclude-directive></div>

After compilation:

<div transclude-directive>
  Some Template
  <span ng-transclude>Some transcluded content</span>
</div>

If the directive is using 'element' transclusion, the compiler will actually remove the directive's entire element from the DOM and replace it with a comment node. The compiler then inserts the directive's template "after" this comment node, as a sibling.

Before compilation

<div element-transclude>
  Some Content
</div>

After transclusion extraction

<!-- elementTransclude -->

After compilation:

<!-- elementTransclude -->
<div element-transclude>
  Some Template
  <span ng-transclude>Some transcluded content</span>
</div>

It is important to be aware of this when writing tests for directives that use 'element' transclusion. If you place the directive on the root element of the DOM fragment that you pass to $compile, then the DOM node returned from the linking function will be the comment node and you will lose the ability to access the template and transcluded content.

var node = $compile('<div element-transclude></div>')($rootScope);
expect(node[0].nodeType).toEqual(node.COMMENT_NODE);
expect(node[1]).toBeUndefined();

To cope with this you simply ensure that your 'element' transclude directive is wrapped in an element, such as a <div>.

var node = $compile('<div><div element-transclude></div></div>')($rootScope);
var contents = node.contents();
expect(contents[0].nodeType).toEqual(node.COMMENT_NODE);
expect(contents[1].nodeType).toEqual(node.ELEMENT_NODE);

Testing Directives With External Templates

If your directive uses templateUrl, consider using karma-ng-html2js-preprocessor to pre-compile HTML templates and thus avoid having to load them over HTTP during test execution. Otherwise you may run into issues if the test directory hierarchy differs from the application's.

Testing Promises

When testing promises, it's important to know that the resolution of promises is tied to the digest cycle. That means a promise's then, catch and finally callback functions are only called after a digest has run. In tests, you can trigger a digest by calling a scope's $applyfunction. If you don't have a scope in your test, you can inject the $rootScope and call $apply on it. There is also an example of testing promises in the $q service documentation.

**Using **<strong>beforeAll()</strong>

Jasmine's beforeAll() and mocha's before() hooks are often useful for sharing test setup - either to reduce test run-time or simply to make for more focused test cases.

By default, ngMock will create an injector per test case to ensure your tests do not affect each other. However, if we want to use beforeAll(), ngMock will have to create the injector before any test cases are run, and share that injector through all the cases for that describe. That is where module.sharedInjector() comes in. When it's called within a describe block, a single injector is shared between all hooks and test cases run in that block.

In the example below we are testing a service that takes a long time to generate its answer. To avoid having all of the assertions we want to write in a single test case, module.sharedInjector() and Jasmine's beforeAll() are used to run the service only once. The test cases then all make assertions about the properties added to the service instance.

describe("Deep Thought", function() {

  module.sharedInjector();

  beforeAll(module("UltimateQuestion"));

  beforeAll(inject(function(DeepThought) {
    expect(DeepThought.answer).toBeUndefined();
    DeepThought.generateAnswer();
  }));

  it("has calculated the answer correctly", inject(function(DeepThought) {
    // Because of sharedInjector, we have access to the instance of the DeepThought service
    // that was provided to the beforeAll() hook. Therefore we can test the generated answer
    expect(DeepThought.answer).toBe(42);
  }));

  it("has calculated the answer within the expected time", inject(function(DeepThought) {
    expect(DeepThought.runTimeMillennia).toBeLessThan(8000);
  }));

  it("has double checked the answer", inject(function(DeepThought) {
    expect(DeepThought.absolutelySureItIsTheRightAnswer).toBe(true);
  }));

});

Sample project

See the angular-seed project for an example.

Thanks For Visiting, Keep Visiting.