Skip to content

Instantly share code, notes, and snippets.

@bignimbus
Last active August 1, 2016 18:46
Show Gist options
  • Save bignimbus/af454f0b05957eefadbfbbc8c864b2db to your computer and use it in GitHub Desktop.
Save bignimbus/af454f0b05957eefadbfbbc8c864b2db to your computer and use it in GitHub Desktop.
Writing a unit test for an angular controller or factory that uses Restangular shouldn't be hard, but it is. Here's how to set it up.
angular.factory('foo', ['Restangular', (Restangular) => {
return Restangular.one('foo', 1);
}]);
describe('foo factory', () => {
// ...
// test setup stuff goes here
// ...
let subject, value;
beforeEach(done => {
inject(_foo_ => {
subject = _foo_;
});
// Restangular and $httpBackend require a rootScope instance because reasons
$scope = $rootScope.$new();
$httpBackend.expectGET('/foo/1').respond({foo: 'bar'});
let promise = subject.get();
// Flushing $httpBackend is required because reasons
$httpBackend.flush();
promise.then(data => {
value = data;
// done is a native jasmine.js function that tells the specrunner to move on to the next task.
// Very handy for async specs.
done();
});
// $scope.$digest() must be called to resolve the promise and trigger the callback
$scope.$digest();
});
afterEach(() => {
value = $scope = subject = null;
});
it('should return value', () => {
expect(value.foo).toBe('bar');
});
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment