[Unit Testing] Karma with Angular mocks
If wants to use karma with AngualrJS, we need to include angular.min-js and angular-mocks.js inside karma.config.js
Be careful with the order, angular.min.js should be first because angular-mock.js depends on it. And directive.spec.js uses inject function in angular-mocks.js, therefore, it should be the last one.
// list of files / patterns to load in the browser files: [ "angular.min.js", "angular-mocks.js", "directive.spec.js", ],
describe("Hello world",function(){
var element;
var $scope;
//1. By using angular, should use inject() function
beforeEach(inject(function($compile, $rootScope){
//2. set up scope to rootScope
$scope = $rootScope;
element = angular.element("<div>{{2+2}}</div>");
//3. the complie function returns link function, so should invoke()
//and it require scope, so we pass $rootScope
element = $compile(element)($rootScope);
}))
it("Should equals 4",function(){
//4. Last we digest the scope
$scope.$digest();
expect(element.html()).toBe("4");
})
})

浙公网安备 33010602011771号