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

270
Views
Cómo burlarse de una const exportada en broma

Tengo un archivo que se basa en una variable const exportada. Esta variable se establece en true , pero si alguna vez es necesario, se puede establecer en false manualmente para evitar algún comportamiento si los servicios posteriores lo solicitan.

No estoy seguro de cómo simular una variable const en Jest para poder cambiar su valor para probar las condiciones true y false .

Ejemplo:

 //constants module export const ENABLED = true; //allowThrough module import { ENABLED } from './constants'; export function allowThrough(data) { return (data && ENABLED === true) } // jest test import { allowThrough } from './allowThrough'; import { ENABLED } from './constants'; describe('allowThrough', () => { test('success', () => { expect(ENABLED).toBE(true); expect(allowThrough({value: 1})).toBe(true); }); test('fail, ENABLED === false', () => { //how do I override the value of ENABLED here? expect(ENABLED).toBe(false) // won't work because enabled is a const expect(allowThrough({value: 1})).toBe(true); //fails because ENABLED is still true }); });
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Este ejemplo funcionará si compila la sintaxis de módulos ES6 en ES5, porque al final, todas las exportaciones de módulos pertenecen al mismo objeto, que se puede modificar.

 import { allowThrough } from './allowThrough'; import { ENABLED } from './constants'; import * as constants from './constants'; describe('allowThrough', () => { test('success', () => { constants.ENABLED = true; expect(ENABLED).toBe(true); expect(allowThrough({ value: 1 })).toBe(true); }); test('fail, ENABLED === false', () => { constants.ENABLED = false; expect(ENABLED).toBe(false); expect(allowThrough({ value: 1 })).toBe(false); }); });

Alternativamente, puede cambiar a la función commonjs require raw, y hacerlo así con la ayuda de jest.mock(...) :

 const mockTrue = { ENABLED: true }; const mockFalse = { ENABLED: false }; describe('allowThrough', () => { beforeEach(() => { jest.resetModules(); }); test('success', () => { jest.mock('./constants', () => mockTrue) const { ENABLED } = require('./constants'); const { allowThrough } = require('./allowThrough'); expect(ENABLED).toBe(true); expect(allowThrough({ value: 1 })).toBe(true); }); test('fail, ENABLED === false', () => { jest.mock('./constants', () => mockFalse) const { ENABLED } = require('./constants'); const { allowThrough } = require('./allowThrough'); expect(ENABLED).toBe(false); expect(allowThrough({ value: 1 })).toBe(false); }); });
over 4 years ago · Santiago Trujillo Report

0

Hay otra forma de hacerlo en ES6+ y jest 22.1.0+ gracias a getters y spyOn.

De forma predeterminada, no puede espiar tipos primitivos como booleano o número. Sin embargo, puede reemplazar un archivo importado con su propio simulacro. Un método captador todavía actúa como un miembro primitivo pero nos permite espiarlo. Al tener un espía en nuestro miembro objetivo, básicamente puedes hacer con él lo que quieras, al igual que con un simulacro de jest.fn() .

Debajo de un ejemplo

 // foo.js export const foo = true; // could be expression as well
 // subject.js import { foo } from './foo' export default () => foo
 // subject.spec.js import subject from './subject' jest.mock('./foo', () => ({ get foo () { return true // set some default value } })) describe('subject', () => { const mySpy = jest.spyOn(subject.default, 'foo', 'get') it('foo returns true', () => { expect(subject.foo).toBe(true) }) it('foo returns false', () => { mySpy.mockReturnValueOnce(false) expect(subject.foo).toBe(false) }) })

Lea más en los documentos.

over 4 years ago · Santiago Trujillo Report

0

Desafortunadamente, ninguna de las soluciones publicadas funcionó para mí o, para ser más precisos, algunas funcionaron pero arrojaron errores de pelusa, TypeScript o compilación, por lo que publicaré mi solución que funciona para mí y cumple con los estándares de codificación actuales:

 // constants.ts // configuration file with defined constant(s) export const someConstantValue = true;
 // module.ts // this module uses the defined constants import { someConstantValue } from './constants'; export const someCheck = () => someConstantValue ? 'true' : 'false';
 // module.test.ts // this is the test file for module.ts import { someCheck } from './module'; // Jest specifies that the variable must start with `mock` const mockSomeConstantValueGetter = jest.fn(); jest.mock('./constants', () => ({ get someConstantValue() { return mockSomeConstantValueGetter(); }, })); describe('someCheck', () => { it('returns "true" if someConstantValue is true', () => { mockSomeConstantValueGetter.mockReturnValue(true); expect(someCheck()).toEqual('true'); }); it('returns "false" if someConstantValue is false', () => { mockSomeConstantValueGetter.mockReturnValue(false); expect(someCheck()).toEqual('false'); }); });
over 4 years ago · Santiago Trujillo 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!