简体   繁体   中英

JSDOM function does not finish

Please help me understand what is wrong here:

Here is my js code (simplified to isolate the minimal code required to demonstrate the problem):

'use strict';
var jsdom = require('jsdom');
describe('desc', function () {
    it('should', function () {
        function uploadURL(callback) {
            jsdom.env({
                url: "http://digg.com",
                done: function (errors, window) {
                    console.log("inside");
                    callback("abc");
                }
            });
        }

        uploadURL(function(x){
            console.log("returned " + x);
        });
    });
});

Here is my command line:

node_modules/mocha/bin/mocha tests/test.js

When I run the above script, I'm getting the following output:

  desc
    ✓ should (196ms)
  1 passing (204ms)

Once I remove the jsdom part and run only the part of the uploadURL() that contains console.log and callback, I get this back:

desc
inside
returned abc
    ✓ should
  1 passing (5ms)

Seems like the jsdom part is not get executed before the script ends. Why is this and how can this be worked out?

Thank you!

Because it's asynchronous. To test an asynchronous function with Mocha, you accept the callback Mocha's it provides, and call it when the async is done:

'use strict';
var jsdom = require('jsdom');
describe('desc', function () {
    it('should', function (done) {
    //                     ^---------------------- accept the callback
        function uploadURL(callback) {
            jsdom.env({
                url: "http://digg.com",
                done: function (errors, window) {
                    console.log("inside");
                    callback("abc");
                }
            });
        }

        uploadURL(function(x){
            console.log("returned " + x);
            done();                            // <=== Call it
        });
    });
});

This is covered in the Mocha documentation here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM