Ricardo Rocha
Ricardo Rocha

Reputation: 16236

jasmine + karma test runner: how to test window.location.href

I have a service that ecapsulate the use of the window object:

@Injectable()
export class WindowService {
    constructor(){};
    get window() : Window {
        return window;
    }
    get href(): string {
        return window.location.href;
    }
    set href(url: string) {
        window.location.href = url;
    }
}

Then I have the following jasmine test:

describe('WindowService Test Suite', () => {
    let windowService: WindowService;

    beforeEach(() => { 
        windowService = new WindowService();
    });

    it('should set the href', () => {
        windowService.href = "/test";
        expect(windowService.href).toBe("/test");
    });
});

The problem is that when I set the href, the karma redirect to the that url and lead to the others test not being runned.

Any one could give some tip I can test this feature without being redirect?

Upvotes: 1

Views: 14402

Answers (2)

Damian Dziaduch
Damian Dziaduch

Reputation: 2127

The only way to test this is to have ability to set window in WindowService via constructor or via setter to fake object. You can't spy or modify window.location...

Upvotes: 1

mzoabi
mzoabi

Reputation: 369

you can do simple trick :

it('should set the href', () => {
    var currentUrl = windowService.href;
    windowService.href = "#test";
    expect(windowService.href).toBe(currentUrl + "#test");
});

the value #test will not redirect your page, but will search DIV with id=test to scroll to it.

Upvotes: 4

Related Questions