zl程序教程

您现在的位置是:首页 >  前端

当前栏目

Angular jasmine单元测试框架里describe的实现原理

Angular框架原理 实现 单元测试 Jasmine
2023-09-14 09:04:02 时间

源代码:describe函数传入的两个参数:描述信息和箭头函数:

从注释能看出,describe函数的语义:Create a group of specs (often called a suite)

getJasmineRequireObj().interface = function(jasmine, env) {
  var jasmineInterface = {
    /**
     * Callback passed to parts of the Jasmine base interface.
     *
     * By default Jasmine assumes this function completes synchronously.
     * If you have code that you need to test asynchronously, you can declare that you receive a `done` callback, return a Promise, or use the `async` keyword if it is supported in your environment.
     * @callback implementationCallback
     * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on.
     * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion.
     */

    /**
     * Create a group of specs (often called a suite).
     *
     * Calls to `describe` can be nested within other calls to compose your suite as a tree.
     * @name describe
     * @since 1.3.0
     * @function
     * @global
     * @param {String} description Textual description of the group
     * @param {Function} specDefinitions Function for Jasmine to invoke that will define inner suites and specs
     */
    describe: function(description, specDefinitions) {
      return env.describe(description, specDefinitions);
    },

参数定义

  • description:Textual description of the group
  • specDefinitions: Function for Jasmine to invoke that will define inner suites and specs

从这里能看出,单元测试代码运行于一个特定的zone里:

 // Monkey patch all of the jasmine DSL so that each function runs in appropriate zone.
        var jasmineEnv = jasmine.getEnv();
        ['describe', 'xdescribe', 'fdescribe'].forEach(function (methodName) {
            var originalJasmineFn = jasmineEnv[methodName];
            jasmineEnv[methodName] = function (description, specDefinitions) {
                return originalJasmineFn.call(this, description, wrapDescribeInZone(specDefinitions));
            };
        });

addSpecsToSuite:

添加Specs到Suite之后,执行:

 /**
         * Gets a function wrapping the body of a Jasmine `describe` block to execute in a
         * synchronous-only zone.
         */
        function wrapDescribeInZone(describeBody) {
            return function () {
                return syncZone.run(describeBody, this, arguments);
            };
        }

在一个同步zone里执行spec的body,即传入describe方法的箭头函数:

callback就是应用程序单元测试代码里定义的箭头函数:

即如下图所示:

更多Jerry的原创文章,尽在:“汪子熙”: