Unit Testing

1 - Asynchronous Javascript Styles
2 - Promises and Async/Await in CC2
3 - fakeAsync() vs async() vs waitForAsync() + tick() in BYOD
4 - setTimeout() and $timeout and jasmine.clock()


Good Opportunity to...ROCK!

Review my code

Optimize it

Comment it

Kick back

Things that make testing more difficult

Spies

​Asynchronous code

Dependencies / Mocks

Dates / Timezones

JS Frameworks / 3rd Party Libraries

The DOM

Async things

1 - Non-promises setTimeout(), $timeout, alert()

2 - Promises using .then() chaining

3 - Async/Await promises

4 - RxJs (Observables)

5 - $q.defer()
(AngularJS's promise library before promises were main stream)

jasmine.clock()

using jasmine clock for setTimeout()

 

.tick() is part of jasmine.clock()??? Could waitForAsync() and fakeAsync() be a wrapper on jasmine.clock() ???? 

jasmine.clock().install();

let value = controller.myFunction();
jasmine.clock().tick(2000);

expect(value).toBe("not undefined");

jasmine.clock().uninstall();

Testing Async

// Typescript
public async saveCarePlan(): Promise<void> {
  try {
  	await this.handleModuleInfoSave(moduleInfo, patient);
  	await this.handleMedicationsSave();
  } catch(error) {
  	// if any trouble saving module info or medications a failure message to display
	this.NotifyService.danger(this.$translate.instant('careplan.metrics.error'));
  }
}
    
    
it('should call show danger message if an error', (done) => {
            spyOn(controller, "preSaveCheckForPCVPhone").and.returnValue(Promise.resolve());
            spyOn(controller, "handleModuleInfoSave").and.returnValue(Promise.resolve());
            spyOn(controller, "handleMedicationsSave").and.returnValue(Promise.reject()); 
            // handleMedicationSave returning a rejected promise will result in an error, landing in the catch block, resulting in the danger message
            let notifyDangerSpy = spyOn(NotifyService, "danger");
            controller.saveCarePlan()
            .then(() => {
                expect(notifyDangerSpy).toHaveBeenCalled();
                done();
            });
        });

Promises with .then()

jasmine.any(Date)

// 1 - Date
expect(new Date()).toEqual(jasmine.any(Date)); // PASSES

let newMomentDate = moment().toDate();
expect(newMomentDate).toEqual(jasmine.any(Date)); // PASSES

Unit Testing Part 2, Async

By Rich Finelli

Unit Testing Part 2, Async

  • 129