简体   繁体   English

创建类似于Mocha JavaScript的单元测试框架

[英]Creating unit testing framework similar to Mocha JavaScript

I'm working on creating a unit testing framework and I'm trying to figure out how the output is possible of the following section of code without the use of global variables: 我正在创建一个单元测试框架,并且试图弄清楚以下代码部分在不使用全局变量的情况下如何输出:

describe("Test Title", function () {
    it("should return a string", function () {
        /* Assertions here */
    });
});
//OUTPUT: "PASS: Test Title should return a string"

Could someone explain how the it method call somehow manages to get one of its parameters up to describe ? 有人可以解释一下it方法调用如何设法使其参数之一得以describe吗?

If that's not clear, what I'm trying to say is I would like to know how a variable can move through callbacks. 如果不清楚,我想说的是我想知道变量如何在回调中移动。 If I understand what's happening, a method call to an outside function within a callback somehow gets an argument to another outside function. 如果我了解发生了什么,则在回调中调用外部函数的方法会以某种方式获取另一个外部函数的参数。

You're probably thinking that it executes the callback passed to it. 您可能会认为it执行传递给它的回调。 It doesn't. 没有。 It just registers the callback as a test. 它只是将回调注册为测试。

The simplest implementation is for describe to run tests: 最简单的实现用于描述运行测试:

var tests = [];

function describe(description,fn) {
    fn();
    for (var i=0;i<tests.length;i++) {
        try {
            tests[i].fn();
            console.log('FAIL:' + description + ' ' + tests[i].description);
        }
        catch (e) {
            console.log('FAIL:' + description + ' ' + tests[i].description);
        }
    }
}

function it(description,fn) {
    tests.push({
        description: description,
        fn: fn
    });
}

However, from glancing at the Mocha code it seems that even describe doesn't really run the code, only register the test suite for another function to process: 但是,从Mocha代码看一看,似乎describe并没有真正运行该代码,只注册了测试套件即可处理另一个函数:

function describe(description,fn) {
    fn();
    testSuites.push({
        description: description,
        tests: tests.slice(0)
    });
}

But the logic is the same. 但是逻辑是一样的。 Create a data structure with all the values and then process them. 创建具有所有值的数据结构,然后对其进行处理。

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

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