0

I have a method/function in actual JS file(main.js) that goes like this:

function returnPath() {
    return `path=${encodeURIComponent(window.location.href.replace(window.location.origin, ''))}`;
}

Now, in my jasmine spec file (mainSpec.js), I have the below code:

 describe('Test returnPath function', () => {

        it('test the path string returned', () => {

          const window = {
            location: {
                href: "https://www.example.com/hello/world",
                origin: "https://www.example.com/"
            }
          };
          const pathStr = returnPath();

          // assert
          expect(pathStr).toBe('path=hello%2Fworld');
        });

      });

But, when I run my test, it fails as the window.location.href does not point to the custom object initialized in the 'it' block.

How to inject/provide objects needed by the actual function from the spec file?

Kaashan
  • 352
  • 3
  • 12
  • This is a scope thing. `returnPath()` has no idea about the `window` object you defined. I think a good idea would be to write `returnPath()` to accept a location object. – Isaac Vidrine Apr 10 '19 at 15:10
  • @Erbsenkoenig: Could you please demonstrate with an example? I don't want to change the implementation/siganture of returnPath function in main.js file – Kaashan Apr 11 '19 at 03:48
  • Ah sorry my comment was misleading. I've deleted it. I've only used that approach when there was a method involved not a property. A mock object seems not to be taken into account. In this post: https://stackoverflow.com/questions/4792281/mocking-window-location-href-in-javascript they suggested to create a method which returns only the window.location.href and one which would return the origin. Than it would be possible to spy on that function with spyOn. But donno whether in that case it's not actually easier/better to change the method signature as suggested. – Erbsenkoenig Apr 11 '19 at 09:04
  • But I just realised, for your use case, do you need a method like this or would it be sufficient to have a service in your project which uses the angular Location from @angular/common, that object allows you to access the current path without having to do the replace bit, and you would be able to test it efficiently using the SpyLocation provided by angular. Here is an example: https://stackblitz.com/edit/location-and-test – Erbsenkoenig Apr 11 '19 at 09:29

0 Answers0