How to Unit Test ES6 Static Class with Sinon (spy/stub/mock)? child function, internal function [JS + SINON]

918 Views Asked by At

Below there is a simplified version of the static class I want to test using Chai, Sinon and Mocha. It exposes 2 functions and has another internal.

//demo.js
const parentFunc = (baseNum) => {
    return childFunc(baseNum, 10);
};

const childFunc = (base, extra) => {
    const sum = base + extra;
    return internalFunc(sum);
};

const internalFunc = (num) => {
    return 100 + num;
};

module.exports = {
    parentFunc: parentFunc,
    childFunc: childFunc
}

Logic is irrelevant, what I want to know is how to spy, stub or mock all the functions of the class to have full UT coverage.

Below there are test cases I want do.

import DemoUtils from '../../src/scripts/common/demo';
import sinon from 'sinon';
import chai from 'chai';

const assert = chai.assert;
const expect = chai.expect;

describe('Demo', () => {
    describe('Internal Function', () => {
        //const res = DemoUtils.internalFunc(8);
    });

    describe('Child Function', () => {
        it('should return ', () => {
            const res = DemoUtils.childFunc(5,10);
            assert.equal(res, 115);
        });

    });

    describe('Parent Function', () => {
        it('should return 140', () => {
            const res = DemoUtils.parentFunc(30);
            assert.equal(res, 140);
        });

        it('should call the child function', () => {
            const stubFunction = sinon.stub(DemoUtils, 'childFunc');
            stubFunction.returns(13);

            const res = DemoUtils.parentFunc(30);
            assert.equal(res, 13);

            assert.equal(stubFunction.calledOnce, true);
            stubFunction.restore();
        });
    });
});
  • Internal Function: I guess internal function can't be tested because couldn't be called/mocked, isn't it?
  • Child Function: test works.
  • Parent Function: first test work but stub function never get called. I tried with spy and mocked too but I can't make it work either.

Anyone has been able to test a ES6 Static Class?

Thanks :)

0

There are 0 best solutions below