Search code examples
angularjasmineangular2-testing

Unit Test with Page object - tests running before Page html elements defined - Angular 2 Jasmine


I have applied the Angular 2 Page Object from the official docs to my tests to simplify setup.

In the docs and so also in my code it has a function called page.addElements that runs in a promise:

  return fixture.whenStable().then(() => {
     // 2nd change detection displays the async-fetched hero
     fixture.detectChanges();
     page.addPageElements();
  });

However for my unit test, page.addElements() is not executing before my it() unit tests. I have placed the function in the same place as the angular 2 docs example haven't I? Why are my it() functions running before my page.addElements()?

It may be because I removed an if condition that wrapped the addPageElements function. It checked to make sure there was a Hero object in the component but my component has no such object that it depends on.

Full spec:

import 'zone.js/dist/long-stack-trace-zone.js';
import 'zone.js/dist/async-test.js';
import 'zone.js/dist/fake-async-test.js';
import 'zone.js/dist/sync-test.js';
import 'zone.js/dist/proxy.js';
import 'zone.js/dist/jasmine-patch.js';

import {
   ComponentFixture,
   TestBed,
   async,
   fakeAsync,
   inject
} from '@angular/core/testing';
import {
   BrowserDynamicTestingModule,
   platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { Router } from '@angular/router';

import { AboutPageComponent } from './about-page.component';
import { ABOUT_ADD_TEXT,
         ABOUT_WHY_TEXT,
         ABOUT_FIND_TEXT,
         ABOUT_MAIN_TEXT,
         ABOUT_RATE_REVIEW_TEXT } from '../resources/strings'

import { click } from '../test/utilities.spec'

describe('AboutPageComponent', () => {
   let component: AboutPageComponent;
   let fixture: ComponentFixture<AboutPageComponent>;
   let debugElement: DebugElement;
   let element: HTMLElement;
   let page: Page;
   let expectedBlurbTitle: string;

   beforeAll(() => {
      TestBed.resetTestEnvironment();
      TestBed.initTestEnvironment(
         BrowserDynamicTestingModule,
         platformBrowserDynamicTesting()
      );
   });

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

   beforeEach(() => {
      expectedBlurbTitle = "blurb title?";
      createComponent();
   });

   function createComponent() {
      fixture = TestBed.createComponent(AboutPageComponent);
      component = fixture.componentInstance;
      page = new Page();

      // 1st change detection triggers ngOnInit
      fixture.detectChanges();
      return fixture.whenStable().then(() => {
         // 2nd change detection displays the async-fetched hero
         fixture.detectChanges();
         page.addPageElements();
      });
   }

   it('should display the base blurb', () => {
      expect(page.blurbHeadingDisplay.textContent).toBe(expectedBlurbTitle);
      expect(page.blurbDisplay.textContent).toBe(ABOUT_MAIN_TEXT);
   });

   it('should display the "why" blurb when hovering over why', () => {
      click(page.whyCircle);
      expect(page.blurbDisplay.textContent).toBe(ABOUT_WHY_TEXT);
   });


   class Page {
      navSpy: jasmine.Spy;
      blurbHeadingDisplay: HTMLElement;
      blurbDisplay: HTMLElement;
      whyCircle: HTMLElement;
      findCircle: HTMLElement;
      addCircle: HTMLElement;
      rateCircle: HTMLElement;

      /** Add page elements after hero arrives */
      addPageElements() {
         this.whyCircle = fixture.debugElement.query(By.css('#why')).nativeElement;
         this.findCircle = fixture.debugElement.query(By.css('#find')).nativeElement;
         this.addCircle = fixture.debugElement.query(By.css('#add')).nativeElement;
         this.rateCircle = fixture.debugElement.query(By.css('#rate-review')).nativeElement;
         this.blurbHeadingDisplay = fixture.debugElement.query(By.css('h1:nth-of-type(3)')).nativeElement;
         this.blurbDisplay = fixture.debugElement.query(By.css('p:first-of-type')).nativeElement;
      }
   }
});

Solution

  • Now that an extra async task is required:

    return fixture.whenStable().then(() => {
    

    both beforeEach's need to have the async testing utility:

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [
                MiddleRowComponent,
                CirclesComponent,
                ButtonComponent
            ],
            providers: [{
                provide: Router,
                useClass: class {
                    navigateByUrl(url: string) { return url; }
                }
            }]
        }).compileComponents();
    }));
    
    beforeEach(async(() => {
        fixture = TestBed.createComponent(MiddleRowComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
        createComponent();
    }));