3. Test HomeComponent

In this section we will introduce unit testing.

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.

  • 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.

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.

You can read more about the benefits of using Jest over Jasmine for your Angular unit tests at the jest blog. They are both great but we will be using Jest. You can read more about the Angular jest package on github.

  • 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.

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.

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.

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.

src/app/app.component.spec.ts
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');
  }));
});

3. Swap out Jasmine for Jest

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.

You can read more about the benefits of using Jest over Jasmine for your Angular unit tests here jest blog. They are both great but we will be using Jest. You can read more about the package the Angular jest package on github.

  • 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

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.

wallaby.js
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'
  };
};

5. Start wallaby

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.

  • Start wallaby.js by pressing "Ctrl + Shift + P" and searching for wallaby start.

  • When prompted for choosing a config file choose "wallaby.js"

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.

src/app/home/home.component.spec.ts
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');
  });
});

StackBlitz Link

Last updated