I'm currently facing an issue with unit testing a function in my controller. The problem lies in making a $scope
variable testable. I am assigning the variable within the .then()
block of my controller and need to ensure it is set correctly when the .then block is executed.
This is the snippet of my controller code:
function submit() {
myService.submit().then(function(responseData){
if(!responseData.errors) {
$scope.complete = true;
$scope.details = [
{
value: $scope.formattedCurrentDate
},
{
value: "$" + $scope.premium.toFixed(2)
},
];
} else {
$scope.submitError = true;
}
});
}
The specifics of where this service call leads are not important. It will return JSON with
action: 'submitted', 'response' : 'some response'
. The .then() method checks for errors in the responseData, and if none are found, it should set certain details. I am attempting to test these $scope.details in my unit test below:
it('should handle submit details', function () {
var result;
var premium = 123.45;
var formattedCurrentDate = "2016-01-04";
var promise = myService.submit();
mockResponse = {
action: 'submitted',
response: 'some response'
};
var mockDetails = [
{
value: formattedCurrentDate
},
{
value: "$"+ premium.toFixed(2)
}
];
//Resolve the promise and store results
promise.then(function(res) {
result = res;
});
//Apply scope changes
$scope.$apply();
expect(mockDetails).toEqual(submitController.details);
});
Now, I am encountering an error stating that $scope.details is undefined. I am unsure how to make the test recognize the change in $scope data within the controller.
In the beforeEach section and other functions in my unit test:
function mockPromise() {
return {
then: function(callback) {
if (callback) {
callback(mockResponse);
}
}
}
}
beforeEach(function() {
mockResponse = {};
module('myApp');
module(function($provide) {
$provide.service('myService', function() {
this.submit = jasmine.createSpy('submit').and.callFake(mockPromise);
});
});
inject(function($injector) {
$q = $injector.get('$q');
$controller = $injector.get('$controller');
$scope = $injector.get('$rootScope');
myService = $injector.get('myService');
submitController = $controller('myController', { $scope: $scope, $q : $q, myService: myService});
});
});
What steps can I take to resolve the promise within my unit test so that I can use $scope.$digest() to observe the changes in the $scope variable?