简体   繁体   中英

Using ajax-post within mocha test reporter fails

i'm tyring to send my mocha test results with jquery post to my API. So I wrote a custom reporter:

var mocha = require('mocha');
var $ = require('jquery');
module.exports = Reporter

function Reporter(runner) {
    mocha.reporters.Base.call(this, runner);
    var passes = 0;
    var failures = 0;

    runner.on('pass', function (test) {
        passes++;
    });

    runner.on('fail', function (test, err) {
        failures++;
    });

    runner.on('end', function () {
        data = {
            date: formatDate(new Date()),
            passed: passes,
            failed: failures
        }

       $.ajax({
            url: "https://localhost:8080/test/results",
            method: "POST",
            data: data,
            dataType: "json",
            success: function () {
                console.log("sent");
            },
            error: function () {
                console.log("failed");
            }
        });

    });
}

I used npm i jquery and it added "jquery": "^3.4.1" into my package.json

But when I execute mocha tests, it throws an exception, that $.ajax is not a function . My research didn't find any helpful results. (And I don't use the slim-version of jquery) Any idea what I did wrong? Or may I not use $.ajax for this?

Initializing jQuery in Node vs in Browser

The problem seems to be with initializing jQuery in Node, which is different than initializing in browser.

Documentation of jQuery npm package, which you can find here , says as follows:

For jQuery to work in Node, a window with a document is required. Since no such window exists natively in Node, one can be mocked by tools such as jsdom. This can be useful for testing purposes.

Instead of simply using below line:

var $ = require('jquery'); // Would work in browser

You should first mock DOM and after that initialize jQuery:

require("jsdom").env("", function(err, window) {
    if (err) {
        console.error(err);
        return;
    }

    var $ = require("jquery")(window);
});

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