Last active
August 1, 2016 18:46
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
angular.factory('foo', ['Restangular', (Restangular) => { | |
return Restangular.one('foo', 1); | |
}]); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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