I have a function in a controller that has a call
var someVar = angular.element(event.target).scope().field;
I am trying to mock it by doing
var ngElementFake = function(el) {
return {
scope: function() {
return {
toggleChildElement: true,
field: scope.field
}
}
}
}
spyOn(angular, 'element').andCallFake(ngElementFake);
However when I call the function in the test I get the response:
TypeError: 'undefined' is not a function (evaluating 'injector.get('$rootElement').off()')
at ../angular-mocks/angular-mocks.js:1819
What am I doing wrong?
EDIT: Injection
beforeEach(function() {
inject(function($rootScope, $controller) {
scope = $rootScope;
scope.record = recordData;
scope.model = 'Hierarchy';
ctrl = $controller("fngHierarchyChildCtrl", {
$scope: scope
});
});
});
A mock component in Angular tests can be created by MockComponent function. The mock component respects the interface of its original component, but all its methods are dummies. To create a mock component, simply pass its class into MockComponent function.
First define a variable like this: let authService: AuthService; Then once the testbed has been set up, set this to the actual service being used by the TestBed inside the last beforeEach() : authService = TestBed.
To run your tests using the Angular CLI, you use the ng test command in your terminal. As a result, Karma will open up the default browser and run all the tests written with the aid of Jasmine and will display the outcome of those tests.
Mocking is the act of creating something that looks like the dependency but is something we control in our test. There are a few methods we can use to create mocks.
I was able to fix this by manually clearing the spy in an after callback.
var spy;
beforeEach(function() {
spy = spyOn(angular, 'element').andCallFake(ngElementFake);
});
afterEach(function() {
spy.andCallThrough();
});
From the AngularJS FAQ:
Due to a change to use on()/off() rather than bind()/unbind(), Angular 1.2 only operates with jQuery 1.7.1 or above.
So, try upgrading to jquery 1.7.1 or above or don't use jquery at all and angular will use its own jQLite.
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