Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

136
Views
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')
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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)
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!