1

I want to mock window.location.origin in my unit test. I have tried to edit it directly. but it said that the location object is readonly.

I can't find other way.Could you help me?

e,g

function login(){
if(window.location.origin) {
    window.location.href = 'https://stackoverflow.com';
}}

How can I test the login() function?

Emon
  • 1,401
  • 14
  • 24
  • try stubbing window location.. like [mocking window.location.href in Javascript](https://stackoverflow.com/questions/4792281/mocking-window-location-href-in-javascript) – rmjoia Apr 16 '19 at 10:28
  • I still don't understand how to handle it .. – Emon Apr 17 '19 at 02:17
  • It wuold be easier for everyone if you could provide some code of what you are doing and what is going wrong. [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) – rmjoia Apr 17 '19 at 07:33

1 Answers1

0

Finally, we found a way to mock window object by below code:

    windowRedirect(localWindow) {
    const windowObj = localWindow || window;
    windowObj.location.href = 'https://www.google.com';
    }

UT:

    it('Test window', (done: DoneFn)=> {
    const localWindow = {
        location: {
            href: 'currentUrl'
        }
    };
    component.windowRedirect(localWindow);
    expect(localWindow.location.href = 'https://www.google.com');
    done();
   });

I think it's still a temporary solution. Please add your comment if you have any other idea.

Emon
  • 1,401
  • 14
  • 24