mercredi 22 juin 2016

Unit testing AngularJS promises with ES6

I'm trying to test an async method in an AngularJS service that calls another async function internally using Jasmine and Karma.

Here's how my service looks like:

export default class SearchUserAPI {

  constructor(BaseService, $q) {
    this.q_ = $q;
    this.service_ = BaseService;
  }

  isActive(email) {
    const params = {'email': email};

    return this.service_.getUser(params).then(isActive => {
      // This part cannot be reached.
      console.log('Is Active');
      // I need to test the following logic.
      return isActive ? true : this.q_.reject(`User ${email} is not active.`);
    });
  }
}

And here's how my test looks like:

import SearchUserApi from './api.service';

let service,
    mockedService,
    $q;

const email = 'chuck.norris@openx.com';
const expectedParams = {email: email};

describe('Search API unit tests', function() {

  beforeEach(inject(_$q_ => {
    $q = _$q_;
    mockedService = {};

    service = new SearchUserApi(mockedService, $q);
  }));

  // This test passes, but it doesn't reach the logging statement in main method.
  it('is verifying that Chuck Norris should be active', () => {
    // Trying to mock getUser() to return a promise that resolves to true.
    mockedService.getUser = jasmine.createSpy('getUser').and.returnValue($q.when(true));

    service.isActive(email).then(result => {
      // The following should fail, but since this part is called asynchronously and tests end before this expression is called, I never get an error for this.
      expect(result).toBe(false);
    });
    // This test passes, but I'm not too sure how I can verify that isActive(email) returns true for user.
    expect(mockedService.getUser).toHaveBeenCalledWith(expectedParams);
  });
});

I see in a lot of tutorials, they talk about using $scope and apply to see if a scope variable has been changed. But in my case, I'm not manipulating any instance(scope) variable to use $scope.apply().

Any idea how I can make the test to wait for my async calls to be resolved before they end?

Aucun commentaire:

Enregistrer un commentaire