Search code examples
jasminekarma-jasminebrowserifycommonjsistanbul

karma-jasmine - how to test return object


I'm trying to add a test that will cover the return statement in the CommonJS file, module1.js, please see the attached image.

Here's what I'm currently trying:

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();
    });
});

Module1 file:

/**
 * 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 output:

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

UPDATE: When I log mod.module.toString, the console logs:

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

Why isn't my module there?

Am I trying the right approach here? Why doesn't mod.module1(); work?

Istanbul coverage Report


Solution

  • When you set spy on object method in Jasmine the original function is not called. So in your example mod.module1() doesn call actual module function but only spy wrapper function - the actual function is not called at all.
    If you want original function to be called you should use and.callThrough:

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