karma-runner / karma-runner/karma

Trying to understand behavior of globals when loading tests

Open
#2,240 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
12k
Forks
1.7k
PR merge metrics
No merged PRs in 30d

Description

In the process of setting up Karma to test our frontend, I ran into issues getting [sinon.js](sinonjs.org) to work correctly. Sinon relies on detecting the existence of `global.XMLHttpRequest` to stub out their fake HTTP Server.

It turns out that something in the Karma + PhantomJS stack normally sets `global.XMLHttpRequest`. But if an imported JS file tries to set globals itself by using the following snippet, it's no longer set.

```
if (window.global == null) { // Generated by coffeescript's ?= operator
window.global = {};
}
```

I suspect I may be missing a detail on the behavior of window vs global.

I'm trying to understand when does `global.XMLHttpRequest` and the rest of global get set during normal initialization? By which tool (Karma or PhantomJS)? And why does that not happen before files are loaded?

You can see a reproducible example here: https://github.com/sean-lynch/karma-global-test
### Expected behavior
- `global.XMLHttpRequest` and other globals would be set before files are loaded, as it would be when loading into a browser
### Actual behavior
- Not set if another file defines a global object while loading.
### Enviroment Details
- Karma version (output of `karma --version`): 0.13.22
- Relevant part of your `karma.config.js` file

files: [
// Fix to solve problem with window.global not being set properly
//{ pattern: 'global.js', watched: false },

// Then load common
'common.js',

// Load project files that are test ready
'test.js'
],
### Steps to reproduce the behaviour
1. Clone https://github.com/sean-lynch/karma-global-test
2. Run `npm install`, then `npm run test` - See that it fails because global is not set
3. Try commenting out `common.js` in the files section of karma.config.js and see that it's fixed.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.