如何将Jasmine单元测试结果作为字符串返回?

Rya*_*ter 2 javascript unit-testing jasmine

我不确定Reporters是否遗漏了一些东西,但是有一种简单的方法可以执行我的单元测试并将结果检索为字符串而不是弄乱控制台或DOM吗?

HoL*_*ieR 7

要做到这一点,你必须实现自己的Reporter,将记录结果并保持文本格式.以下是如何做到这一点的简短示例:

function TextReporter() {
    this.textResult = "";
}

TextReporter.prototype = new jasmine.Reporter();

TextReporter.prototype.onRunnerFinished = function (callback) {
    this.callbackEnd = callback;
};

TextReporter.prototype.reportRunnerResults = function (runner) {        
    // When all the spec are finished //
    var result = runner.results();

    this.textResult += "Test results :: (" + result.passedCount + "/" + result.totalCount + ") :: " + (result.passed() ? "passed" : "failed");
    this.textResult += "\r\n";

    if (this.callbackEnd) {
        this.callbackEnd(this.textResult);
    }
};

TextReporter.prototype.reportSuiteResults = function (suite) {
    // When a group of spec has finished running //
    var result = suite.results();
    var description = suite.description;
}

TextReporter.prototype.reportSpecResults = function(spec) {
    // When a single spec has finished running //
    var result = spec.results();

    this.textResult += "Spec :: " + spec.description + " :: " + (result.passed() ? "passed" : "failed");
    this.textResult += "\r\n";
};
Run Code Online (Sandbox Code Playgroud)

之后,而不是使用HtmlReporter,你可以使用你的TextReporter.

var jasmineEnv = jasmine.getEnv();
jasmineEnv.updateInterval = 1000;

var txtReporter = new TextReporter();
txtReporter.onRunnerFinished(function (text) {
    // Do something with text //
});

jasmineEnv.addReporter(txtReporter);

window.onload = function() {
    jasmineEnv.execute();
};
Run Code Online (Sandbox Code Playgroud)

如果您需要有关自定义报告者的更多信息,您需要知道的是他们必须实现该Reporter界面.