Search code examples
javascriptmockingmocha.jschaisinon

How to mock an imported array and test the using Function


I'm exporting an array:

//constants.js
export const myarray = ['apples', 'oranges', 'pears'];

//checkFunction.js
import myarray from ./constants

function check(value) {
    return myarray.includes(value);
}

I want to be able to mock the array in my testing suite so that I can control its values for different tests. My problem is, using Mocha & Sinon, how do I test the function check() and mock the imported array myarray. If I create a stub for check() how do I get it to consume the mocked myarray?

sinon.stub(checkFunction, 'checkFunction')

Solution

  • You are testing the check function, you should NOT stub it. Like your said, you should mock the myarray in test cases. You could mutate the value of myarray before require/import the checkFunction.js module. Make sure to clear the module cache before running each test case, so that subsequent imports of the constants module will give you a fresh myarray, not the mutated one.

    E.g.

    constants.js:

    export const myarray = ['apples', 'oranges', 'pears'];
    

    checkFunction.js:

    import { myarray } from './constants';
    
    export function check(value) {
      console.log('myarray: ', myarray);
      return myarray.includes(value);
    }
    

    checkFunction.test.js:

    import { expect } from 'chai';
    
    describe('72411318', () => {
      beforeEach(() => {
        delete require.cache[require.resolve('./checkFunction')];
        delete require.cache[require.resolve('./constants')];
      });
      it('should pass', () => {
        const { myarray } = require('./constants');
        myarray.splice(0, myarray.length);
        myarray.push('beef', 'lobster');
        const { check } = require('./checkFunction');
        expect(check('apples')).to.be.false;
      });
    
      it('should pass 2', () => {
        const { check } = require('./checkFunction');
        expect(check('apples')).to.be.true;
      });
    });
    

    Test result:

      72411318
    myarray:  [ 'beef', 'lobster' ]
        ✓ should pass (194ms)
    myarray:  [ 'apples', 'oranges', 'pears' ]
        ✓ should pass 2
    
    
      2 passing (204ms)