Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

137
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda