How to mock browser specific property `window.location.origin` with AVA
Asked Answered
C

0

9

Context

I have Frontend React+Webpack app consuming backend APIs. My Webpack setup depends on window.location.origin the property, for setting up and deployment processes. Currently, I'm using Karma testrunner and am trying to replace it with AVA testrunner.

I'm trying to apply AVA with this single entry setup for webpack recipe I'm also applying the JSDOM as dom emulator for the node.

Problem

Some of the tests being bundled, use the location.origin property. Which throws an error during running webpack && ava script:

var apiUrl = process.env.API_URL && process.env.NODE_ENV !== 'production' ? process.env.API_URL : location.origin;
ReferenceError: location is not defined

Karma runs on browser engine and reproduces the value of window.location.origin dynamically. With AVA is different. It doesn't run browser of any kind when running test. I can only (as far as I know) "emulate" the browser environment with jsdom, and that is what I am trying to do. However specific location.origin property is not supported by jsdom Issue Link

The Question

Could anyone track me to the solution to reproduce the window.location.origin dynamically (environmentally aware) for AVA? I know that I can put it in constant and store it in .env per each environment. But this is another maintenance task I would like to mitigate.

Calcareous answered 23/10, 2017 at 20:32 Comment(4)
You could of course setup a global variable that is created before your tests start. But, why not use typeof location !== 'undefined' && location.origin !== undefined ? location.origin : 'fallback-api-url'? I assume you only set this once. Is that correct?Tito
I'm not setting it up anywhere @AluanHaddad. Karma runs browser during tests and the value is get from the real browser env. And this is as I want it to be. AVA doesn't run browser for tests, so the value is undefined. I wonder if there is any other way to get the real value of this browser property with AVA. Instead of setting it up in the code.Calcareous
you could have a function that fetches the value of window.location.origin in your production code and then mock the return value of this function in your testsNecklace
@MiloszFrejnik what I mean is, do you need to associate the value with jsdom or can you just use an arbitrary value like you do when process.env.NODE_ENV !== 'production'?Tito

© 2022 - 2024 — McMap. All rights reserved.