【问题标题】:karma-jasmine - how to test return objectkarma-jasmine - 如何测试返回对象
【发布时间】:2018-04-01 15:48:40
【问题描述】:

我正在尝试添加一个涵盖 CommonJS 文件中的 return 语句的测试,module1.js,请参阅附图。

这是我目前正在尝试的:

describe("Module 1 ", () => {
    let mod, testMod = null;

    beforeEach(() => {
        mod = {
            module1: require('../src/app/js/module1/module1')
        };

        spyOn(mod, 'module1');
        testMod = mod.module1();
        console.log(testMod);
        console.log(mod.module1);
    });
    it('is executed', () => {
        expect(mod.module1).toHaveBeenCalled();
    });
});

模块 1 文件:

/**
 * Represents module1.
 * @module module1
 */

function module1() {
    let x = 13;

    return {
        getUserAgent: getUserAgent
    };

    /**
     * Return the userAgent of the browser.
     * @func getUserAgent
     */
    function getUserAgent() {
        return window.navigator.userAgent
    }
}

module.exports = module1;

日志输出:

LOG: undefined
LOG: function () { ... }

更新:当我登录 mod.module.toString 时,控制台会记录:

function () { return fn.apply(this, arguments); }

为什么我的模块不在那里?

我在这里尝试正确的方法吗?为什么mod.module1(); 不起作用?

【问题讨论】:

    标签: jasmine karma-jasmine browserify commonjs istanbul


    【解决方案1】:

    当您在 Jasmine 中对对象方法设置 spy 时,不会调用原始函数。 因此,在您的示例中,mod.module1() 不调用实际的模块函数,而只调用 spy 包装函数 - 根本不调用实际函数。
    如果你想调用原始函数,你应该使用and.callThrough:

    spyOn(mod, 'module1').and.callThrough();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-17
      • 2015-12-07
      • 1970-01-01
      • 2020-04-07
      • 2018-01-31
      • 2014-05-04
      • 2017-05-27
      • 1970-01-01
      相关资源
      最近更新 更多