简体   繁体   English

JSDOM功能未完成

[英]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): 这是我的js代码(经过简化以隔离演示问题所需的最少代码):

'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 node_modules / mocha / bin / mocha测试/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: 一旦删除jsdom部分并仅运行包含console.log和callback的uploadURL()部分,我将得到以下信息:

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

Seems like the jsdom part is not get executed before the script ends. 似乎在脚本结束之前未执行jsdom部分。 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: 为了测试与摩卡异步函数,你接受回调摩卡的it提供,并把它当异步完成:

'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 . 此处的Mocha文档中对此进行了介绍。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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