Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

139
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda