Testing Emberjs app using QUnit and Karma fails du

2019-07-29 09:12发布

问题:

I Was testing EmberJs application with Qunit and karma runner and it was working all good. Then I had to integrate faye into the application which went well but then on running my test suite, it shows following error and crashes:

ReferenceError: Faye is not defined

The error is thrown where, I am defining the client in emberjs

client = new Faye.Client(uri);

Though this works in development, staging but not in testing. Overhere, uri = "http://localhost:9292/faye"

faye.js is included in vendor.js(single js file which have all the js plugins including ember.js and ember-data.js itself) which is loaded before app.js(file where above line exists)

回答1:

The reason of that weird behavior is related to the following lines in Faye:

if (typeof module !== 'undefined') module.exports = Faye; else if (typeof window !== 'undefined') window.Faye = Faye;

Source: https://github.com/faye/faye/blob/master/javascript/faye.js#L143
So if module is not undefined(meaning it is defined) then module.exports will be set object, if not, window.Faye will be set.
If you use a debugger and set a breakpoint on that line you will that module is actually defined, why? it is a QUnit global helper method!
Why Faye does this? I guess because it can be run in a NodeJS environment (you can read more about module.exports here).
As I see it you have 2 possible solutions:

  • Require Faye before QUnit.
  • Patch Faye to ignore the existence of module in window.

I've encountered the same behavior while using Teaspoon with QUnit.
Making Teaspoon require Faye before QUnit seems like a bad idea and will be probably in ugly hack.
I've ended up with patching Faye to make it skip the module check, not so beautiful either, but I believe this is reasonable.