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 }); });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); }); });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) }) })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'); }); });