Monday, May 20, 2024
-1
rated 0 times [  5] [ 6]  / answers: 1 / hits: 35865  / 11 Years ago, wed, november 27, 2013, 12:00:00

I've got the following service:



angular.module(services)
.factory(whatever, function($window) {
return {
redirect: function() {
$window.location.replace(http://www.whatever.com);
}
};
});


How to mock $window object in unit test to prevent reloading the page when running tests?



I tried using



spyOn($window.location, 'replace').andReturn(true);



, but it didn't work (still got Some of your tests did a full page reload! error) and



$provide.value('$window', {location: {replace: jasmine.createSpy()}})



, but I was getting an error (Error: [ng:areq] Argument 'fn' is not a function, got Object) with stack trace pointing only to angular own source, so it wasn't very helpful...


More From » unit-testing

 Answers
35

In Chrome (didn't test inother browsers), location.replace is readonly so spyOn wasn't able to replace it.



$provide.value should work. Something must be wrong somewhere in your code.



Here is a working unit test



describe('whatever', function() {
var $window, whatever;

beforeEach(module('services'));

beforeEach(function() {
$window = {location: { replace: jasmine.createSpy()} };

module(function($provide) {
$provide.value('$window', $window);
});

inject(function($injector) {
whatever = $injector.get('whatever');
});
});

it('replace redirects to http://www.whatever.com', function() {
whatever.redirect();
expect($window.location.replace).toHaveBeenCalledWith('http://www.whatever.com');
});
});

[#74025] Tuesday, November 26, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
raymondd

Total Points: 620
Total Questions: 112
Total Answers: 94

Location: Namibia
Member since Mon, Feb 21, 2022
2 Years ago
raymondd questions
Thu, Apr 22, 21, 00:00, 3 Years ago
Thu, Jul 9, 20, 00:00, 4 Years ago
Thu, Apr 9, 20, 00:00, 4 Years ago
Thu, Jul 25, 19, 00:00, 5 Years ago
;