fbpx

Testing exceptions with Async Await

Normally when testing your code throwing exceptions is goes something like this: (examples in typescript with Jasmine)


function isTwo(num: number): number {
  if(num != 2) throw new Error("Yo! It's not number 2!!");
  return num;
}

// ... inside describe block
it("should throw an error", () => {
  const throwError = function() { isTwo(3) };

  expect(throwError).toThrowError("Yo! It's not number2!!")
}

We wrap our function in an anonymous function and pass it to the expectation.  All is good and we move on with our day!

But what if our function is returning a promise! Aha, things can’t work the same.

Let’s use async / await to help us.


function isTwo(num: number): Promise<number> {
  new Promise(resolve, reject) {
    if(num != 2) reject("Yo! It's not number 2!!");
    resolve(num);
  }
}

// ... inside describe block
it("should throw an error", async () => {
  try {
    const throwError = isTwo(3); 
  } catch(error) {
    expect(error.message).toBe(""Yo! It's not number 2!!");
  }
}

Get In the Zone

Using Zones is a great way to escape Angular’s change detection and speed up performance. However, when a 3rd party library uses them, it can cause some confusion and/or unexpected results (Any resemblance to actual persons or events is purely coincidental).

ChangeDetectorRef allows you to manually force change detection and be on your merry way.

import { ChangeDetectorRef } from '@angular/core';
...
export class Zoning {

     constructor(private changeDetector: ChangeDetectorRef) {}
...
    this.codeOutsideOfZone = true;

    // forces change detection
    this.changeDetector.detectChanges();
...
}

Bootstrapping WordPress

Today I came across a situation where I needed to use the wordpress core but did not need the theme as the project had a separate framework for the front end.  To accomplish this you can add the following code to your php file:

<?php
    /** Must be false to disable template! */
    define('WP_USE_THEMES', false);

    /** Loads the WordPress Environment */
    require ('./wp-blog-header.php');

JSON API Resource GEM

Working on a Rails project using JSON API Resource gem I came across an interesting “gotcha”. When making a POST request and the JSON key is multiple words you must use dashes to separate the words, the corresponding incoming param uses underscore.

For example you have the following Model attribute: date_of_birth. JSON API Resource will not accept “date_of_birth” only “date-of-birth”.