Reputation: 4374
I'm using AngularJS and my tests are in mocha+sinon+chai
The code I'm trying to test looks like this:
addModal.result.then(function (clientFeature) {
if (clientFeature) {
//create a new $resource ClientFeature object with result
var newClientFeature = new ClientFeature(clientFeature);
//push newly created clientfeature to list
$scope.clientFeatures.push(newClientFeature);
//make REST call to create new clientfeature
newClientFeature.$save({clientId: newClientFeature.client.id}, function (data, headers) {
console.log('created.');
console.log(data);
}, null);
}
});
ClientFeature is a $resource object:
'use strict';
angular.module('yrdyApp')
.factory('ClientFeature', function ($resource, $location) {
return $resource('https://' + $location.host() + ':port/clientfeatures/client/:clientId', {port: ':3333', clientId: '@clientId'}, {
update: {method: 'PUT'}
});
});
How do I mock out this line?
//create a new $resource ClientFeature object with result
var newClientFeature = new ClientFeature(clientFeature);
My existing mocks:
// set up mocks
ClientFeatureMock = {
query: sinon.spy(),
update: sinon.stub()
};
// mock client feature object
clientFeature = {
client: {
id: 100
},
$update: sinon.spy(),
$save: sinon.spy()
};
Thanks, Shaun
Upvotes: 3
Views: 947
Reputation: 4374
I'm not sure if it's the recommended way of doing things, but I decided to not stub/mock the service. Instead, I'm injecting the actual service, and spying on individual methods + setting up httpBackend to intercept http requests.
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope, _$timeout_, $q, $httpBackend, _ClientFeature_) {
// inject actual service
ClientFeature = _ClientFeature_;
// set up httpBackend behavior
httpBackend = $httpBackend;
httpBackend.whenGET(/https:\/\/.+\/clientfeatures\/client\/./).respond(200, []);
// set up mocks
ClientFeatureMock = {
query: sinon.spy(ClientFeature, 'query')
};
And an example test:
it('should start by retrieving a list of clientfeatures for a client', function () {
// flush/make the http call
httpBackend.flush();
ClientFeatureMock.query.should.be.called;
});
Upvotes: 2