I am trying to create unit test for my controller.
I have something like
angular.module('myApp').controller('testCtrl', ['$scope', 'testFactory',
function($scope, testFactory) {
//I am getting the error when I ran Karma
//TypeError: 'undefined' is not a function (evaluating
//'$scope.$watch')
$scope.$watch(function(){
return testFactory.returnItem; // watch the factory returned data
}, function(newVal){
console.log('call here')
});
}
]}
In my factory file
angular.module('myApp').factory('testFactory', ['Product','$cookies','$q',
function(Product ,$cookies, $q) {
var service = {};
service.getProduct = function() {
var deferred = $q.defer();
var that = this;
Product.query({
Id: 123,
}, function(product) {
that.returnItem = product;
deferred.resolve(product);
});
return deferred.promise;
};
return service;
}
]);
My unit test
describe('Test ', function () {
beforeEach(module('myApp'));
var $controller, testFactory;
// Initialize the controller and a mock scope
beforeEach(inject(function(_$controller_, _testFactory_){
$controller = _$controller_;
testFactory = _testFactory_;
}));
describe('Initial test', function() {
it('should return data', function() {
var $scope = {};
var controlelr = $controller('testCtrl', {$scope:$scope});
//not sure what to do next….
});
});
})
I am stuck at the error message and I am not sure what to do for the factory test. I am not sure how I can test the getProduct
method for my service in the controller.
In the unit test, you need to create a new scope object, not just an empty object literal. And you also need to inject a testFactory object when instantiating your controller. Off the top of my head, something like this:
describe('Test ', function () {
beforeEach(module('myApp'));
var $controller, testFactory, scope;
// Initialize the controller and a mock scope
beforeEach(inject(function(_$controller_, _$rootScope_, _testFactory_){
$controller = _$controller_;
$rootScope = _$rootScope_;
testFactory = _testFactory_;
}));
scope = $rootScope.$new();
describe('Initial test', function() {
it('should return data', function() {
var controller = $controller('testCtrl', {$scope:scope, testFactory:testFactory});
// expect something here
});
});
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With