Estoy exportando una matriz:
//constants.js export const myarray = ['apples', 'oranges', 'pears']; //checkFunction.js import myarray from ./constants function check(value) { return myarray.includes(value); } Quiero poder simular la matriz en mi conjunto de pruebas para poder controlar sus valores para diferentes pruebas. Mi problema es, usando Mocha & Sinon, ¿cómo pruebo la función check() y me burlo de la matriz importada myarray ? Si creo un stub para check() , ¿cómo hago para que consuma el myarray ?
sinon.stub(checkFunction, 'checkFunction')Está probando la función de check , NO debe bloquearla. Como dijiste, deberías burlarte de myarray en casos de prueba. Puede mutar el valor de myarray antes de require / import el módulo checkFunction.js . Asegúrese de borrar el caché del módulo antes de ejecutar cada caso de prueba, de modo que las importaciones posteriores del módulo de constants le proporcionen un myarray nuevo, no uno mutado.
P.ej
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; }); });Resultado de la prueba:
72411318 myarray: [ 'beef', 'lobster' ] ✓ should pass (194ms) myarray: [ 'apples', 'oranges', 'pears' ] ✓ should pass 2 2 passing (204ms)