简体   繁体   English

在Mocha Test Reporter中使用Ajax-Post失败

[英]Using ajax-post within mocha test reporter fails

i'm tyring to send my mocha test results with jquery post to my API. 我想将带有jQuery post的摩卡测试结果发送到我的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 我使用npm i jquery并将其添加到我的package.json中的"jquery": "^3.4.1"

But when I execute mocha tests, it throws an exception, that $.ajax is not a function . 但是,当我执行mocha测试时,会引发异常,即$.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? (而且我不使用jquery的slim版本)知道我做错了什么吗? Or may I not use $.ajax for this? 还是我不能为此使用$.ajax

Initializing jQuery in Node vs in Browser 在Node vs Browser中初始化jQuery

The problem seems to be with initializing jQuery in Node, which is different than initializing in browser. 问题似乎在于在Node中初始化jQuery,这与在浏览器中初始化不同。

Documentation of jQuery npm package, which you can find here , says as follows: 您可以在此处找到jQuery npm软件包的文档,内容如下:

For jQuery to work in Node, a window with a document is required. 为了使jQuery在Node中工作,需要一个带有文档的窗口。 Since no such window exists natively in Node, one can be mocked by tools such as jsdom. 由于Node本身不存在这样的窗口,因此可以通过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: 您应该首先模拟DOM,然后初始化jQuery:

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

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

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

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