---
description: In this section we will introduce unit testing.
---

# 3. Test HomeComponent

{% hint style="info" %}
We will be demonstrating wallaby.js in this workshop which is a paid extension for VS Code and free trial but is not needed to complete this workshop - just a nice to have.
{% endhint %}

* Execute the below command to see results of running the default test suite of Jasmine and Karma. You will have broken tests that were generated when the Angular CLI made default tests.
* There will be some errors in the AppComponent's spec file since we changed the HTML. We are not so interested in these more complete test examples just yet, but we need to get them working before moving on. Copy and paste the code below in app.component.spec.ts, or optionally feel free to delete them as we will build up writing tests like these.

{% hint style="warning" %}
It is a good idea to commit your code before running the following 'ng add' command so you can see both changes and revert it if needed.
{% endhint %}

You can read more about the benefits of using Jest over Jasmine for your Angular unit tests at the [jest blog](https://blog.angularindepth.com/integrate-jest-into-an-angular-application-and-library-163b01d977ce). They are both great but we will be using Jest. You can read more about the Angular  [jest package on github](https://github.com/davinkevin/jest).

* Add the necessary package dependencies first.
* Run the 'ng add' command to add jest to your app. The 'ng add' commands allow us to add and also configure our app saving many tedious error prone steps doing it by hand.

{% hint style="warning" %}
Commit your changes before running any 'ng add' or Angular CLI commands so it is easy to use source control to undo if it is wrong.
{% endhint %}

* Add wallaby by using this 'ng add' command. This will add wallaby to your Angular CLI application.

## [Link to section slides](https://docs.google.com/presentation/d/1Y7Tf7kjO4Li0ihhkVgRjn4szFJPAkbMvilfrDCbrjq8/edit#slide=id.g4271862451_0_24)

{% hint style="info" %}
We will be demonstrating wallaby.js in this workshop which is a paid extension for VSCode and has a free trial but is not needed to complete this workshop just a nice to have.
{% endhint %}

## 1. Start default Karma and Jasmine tests

* Execute the below command to view the results of the default test suite using Jasmine and Karma. You will have broken tests that where generated when the AngularCLI made default tests.

```
ng test
```

## 2. Fix default tests

* There will be some errors on the AppComponent's spec file since we changed the HTML. We are not so interested in these more complete test examples just yet but we might as well get them working. Optionally feel free to delete them as we will build up writing tests like these.

{% code title="src/app/app.component.spec.ts" %}
```typescript
import { TestBed, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ RouterTestingModule],
      declarations: [
        AppComponent
      ],
    }).compileComponents();
  }));
  it('should create the app', async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  }));
  it(`should have as title 'angular-and-ngrx-demo-app'`, async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    const app = fixture.debugElement.componentInstance;
    expect(app.title).toEqual('angular-and-ngrx-demo-app');
  }));
  it('should render title in a h1 tag', async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    fixture.detectChanges();
    const compiled = fixture.debugElement.nativeElement;
    expect(compiled.querySelector('h1').textContent).toContain('The App');
  }));
});
```
{% endcode %}

## 3. Swap out Jasmine for Jest

{% hint style="warning" %}
It is best you commit you code before running this 'ng add' command so you can both see the changes and revert it if needed.
{% endhint %}

You can read more about the benefits of using Jest over Jasmine for your Angular unit tests here [jest blog](https://blog.angularindepth.com/integrate-jest-into-an-angular-application-and-library-163b01d977ce). They are both great but we will be using Jest. You can read more about the package the Angular [jest package on github](https://github.com/davinkevin/jest).

* Best to add the needed package dependencies first.

```
npm i jest-preset-angular jest -D
```

* Run the below 'ng add' command to add jest to your app. The 'ng add' commands allow us to add and also configure our app saving many tedious error prone steps doing it by hand.

```
ng add @davinkevin/jest
```

* Check it is working by running the following command

```
npm test
```

![Image: Terminal showing test runner output of passing tests](https://3531511677-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LLqc06ABPywqowC_y8E%2F-LMQ9VjKCwmvcOCqSOZx%2F-LMQBkcAcyr9QCKPsdtl%2Fimage.png?alt=media\&token=1a7ecd4d-c87b-46ea-84b5-93b9b228acc9)

## 4. Add wallaby.js for unit testing

* !Commit your changes before running any 'ng add' or Angular CLI commands so it is easy to use source control to undo if it is wrong.
* Add wallaby by using this 'ng add' command. This will add wallaby to your Angular CLI application.

```
ng add ngcli-wallaby
```

* We will also need to update this to use jest rather than jasmine as per the sites [instructions](https://wallabyjs.com/docs/integration/angular.html).&#x20;

{% code title="wallaby.js" %}
```javascript
module.exports = function () {

  const jestTransform = file => require('jest-preset-angular/preprocessor').process(file.content, file.path, {globals: {__TRANSFORM_HTML__: true}, rootDir: __dirname});

  return {
    files: [
      'src/**/*.+(ts|html|json|snap|css|less|sass|scss|jpg|jpeg|gif|png|svg)',
      'jest.setup.ts',
      '!src/**/*.spec.ts',
    ],

    tests: ['src/**/*.spec.ts'],

    env: {
      type: 'node',
      runner: 'node'
    },

    compilers: {
      '**/*.html': file => ({code: jestTransform(file), map: {version: 3, sources: [], names: [], mappings: []}, ranges: []})
    },

    preprocessors: {
      'src/**/*.js': jestTransform,
    },

    testFramework: 'jest'
  };
};
```
{% endcode %}

## 5. Start wallaby

{% hint style="info" %}
You should have already installed the WallabyJS extension for Visual Studio Code, if not then please follow these instructions to do so [https://marketplace.visualstudio.com/items?itemName=WallabyJs.wallaby-vscode](https://marketplace.visualstudio.com/items?itemName=WallabyJs.wallaby-vscode).
{% endhint %}

* Start wallaby.js by pressing "Ctrl + Shift + P" and searching for wallaby start.
* When prompted for choosing a config file choose "wallaby.js"

![Image: Visual Studio Code command pallet showing wallaby start](https://3531511677-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LLqc06ABPywqowC_y8E%2F-LLrk2SVzgWHzhabJhrD%2F-LLrmMuqh9iLzw45PgPU%2Fimage.png?alt=media\&token=8c166cf5-0932-4a24-a761-49f466b00f8c)

## 6. Add a simple test for the title property of the HomeComponent

Let's write some simple component tests on our HomeComponent which we will grow on over this course to write more advanced tests. In this test we use Jest's Behaviour Driven Design (BDD) style tests. Do not be concerned about using Jest rather than Jasmine as the default testing tools for Angular because the syntax is virtually the same except for Spys, which we will point out later the differences.

The "describe" block is for suites of tests and the "it" block is an individual test. In this test we simply new up the HomeComponent and check its title property, later we will use Angular's TestBed test helper API to set up our tests.

* Delete the code generated tests in the home.component.spec.ts file we will start from scratch before tackling the auto-generated tests.
* Write a simple test for the HomeComponent.

{% code title="src/app/home/home.component.spec.ts" %}
```typescript
import { HomeComponent } from './home.component';

describe('component: home', () => {
  it('have a title of "The title"', () => {
    const component = new HomeComponent();
    expect(component.title).toEqual('The title');
  });
});
```
{% endcode %}

## StackBlitz Link <a href="#id-3-review-the-structure-and-key-files" id="id-3-review-the-structure-and-key-files"></a>

{% embed url="https://stackblitz.com/github/duncanhunter/angular-and-ngrx-demo-app/tree/3-test-home-component" %}
Web Link: Link to the demo app running in StackBlitz
{% endembed %}
