Async network requests


You want to make network requests or do other asynchronous work in xpcshell. However, when you start your script, it exits immediately, before the network request returns.


1. Put the following at the end of your script:

// Do async processing
// From <>
print("Doing async work");
gScriptDone = false;
var gThreadManager = Cc[";1"]
var mainThread = gThreadManager.currentThread;

while (!gScriptDone)
while (mainThread.hasPendingEvents())

2. In all callbacks where your script is finished, i.e. both success and error callbacks, put:

gScriptDone = true;

If you forget some condition where your script should exit but you don't add this statement, your script will hang (busy wait).

This is of course a massive, ugly hack prone to error, but this is what the xpcshell test harness does. There should really be a better solution in xpcshell.

Using JS modules and non-UI JavaScript chrome files


You want to write a JavaScript file, and run it in xpcshell. The file uses JS modules. Maybe it even uses JavaScript files from chrome:// URLs.

E.g., you use:


However, you get (for that particular line, which is the first import):

uncaught exception: [Exception... "Component returned failure code: 0x80040111 (NS_ERROR_NOT_AVAILABLE) 
[nsIXPCComponents_Utils.import]"  nsresult: "0x80040111 (NS_ERROR_NOT_AVAILABLE)"  location: "JS frame ::
file.js :: <TOP_LEVEL> :: line 12"  data: no]


Solution 1

var loader = Components.classes[";1"]


Solution 2

Append the following at the top of your JS file which you want to run in xpcshell

  // <>
  // <>
  let Cc = Components.classes;
  let Ci = Components.interfaces;

  // Register resource://app/ URI
  let ios = Cc[";1"]
  let resHandler = ios.getProtocolHandler("resource")
  let mozDir = Cc[";1"]
      .get("CurProcD", Ci.nsILocalFile);
  let mozDirURI = ios.newFileURI(mozDir);
  resHandler.setSubstitution("app", mozDirURI);

  // register chrome://* URIs
  let cr = Cc[";1"]

Bug 546628 would make this unnecessary.