2

Here is my setup.

  • I have a grunt task that does 2 things: 1) start a http server listening on some port 2) triggers another grunt task
  • The grunt task triggered above is a testem task that runs tests on test-index.html page in PhantomJS.
  • The test-index.html page sends a POST call on the port on which I start a server in the first grunt task.

Issue: The POST call doesn't hit my server.

Note: If I run the same server manually (not from grunt) and then run the test grunt task, the POST call hits the server.

Heres the code:

Grunt task

grunt.registerMultiTask('coverage', 'Generates coverage reports for JS using Istanbul', function () {
 var server = http.createServer(function(req, resp) {
  resp.setHeader("Access-Control-Allow-Origin", "*");
  console.log('Got something');
  req.pipe(fs.createWriteStream('coverage.json'))
  resp.end();
 });
 var port = 7358;
 server.listen(port);

 // This task simply executes a command: `testem.js ci`
 grunt.task.run('testem').then(function() {
  server.close();
 });
});

test-index.html (somewhere in the )

function onTestemLoad() {
 Testem.on('all-test-results', function(results){
  var xhr = new XMLHttpRequest();
  xhr.open('POST', 'http://localhost:7358/');
  xhr.send(JSON.stringify(window.__coverage__))
 });
}

Can anyone point what might be going wrong here?

Kushagra Gour
  • 4,568
  • 2
  • 22
  • 26

1 Answers1

0

you've been misled by grunt.task.run! This line does NOT run the task, it just puts it on the top of the list of tasks to run once the current task is done (http://gruntjs.com/api/grunt.task#grunt.task.run).

A second issue is that when a task completes, it takes down all its running processes with it.

So what happens is:

  1. coverage starts, spins on your server, then register testem as next task
  2. coverage ends, taking down your server
  3. next task (= testem) runs, but no server is here to answer...

You can fix it by doing the following 2 things:

  • inline your test: replace grunt.task.run('testem') with a direct call to testem
  • ensure your tests run synchronously - or keep your task alive until your tests are done (using this.async - see http://gruntjs.com/api/inside-tasks#this.async).
Xavier Priour
  • 2,121
  • 1
  • 12
  • 16