Imaginemos que tengo un módulo como el siguiente:
// utils.ts function innerFunction() { return 28; } function testing() { return innerFunction(); } export {testing} Me gustaría escribir una prueba unitaria para probar las testing y simplemente simular el valor de retorno de innerFunction , esperando que cualquier llamada a innerFunction se resuelva en un cierto valor, algo como a continuación:
jest.mock('../utils', () => { const originalModule = jest.requireActual('../utils'); return { // __esModule: true, ...originalModule, innerFunction: jest.fn().mockReturnValue(33), }; }); import { testing } from '../utils'; it('should be okay', () => { expect(testing()).toBe(33); }); Esperaba que jest.requireActual pudiera leer todas las funciones e innerFunction: jest.fn().mockReturnValue(33) en realidad causará que cualquier invocación de innerFunction solo devuelva 33 como valor, pero del pequeño experimento anterior parece que es no es el caso.
En la llamada real, la innerFunction devolverá 28 , pero en el entorno Jest me gustaría que la innerFunction pueda resolver cualquier valor que me gustaría
Intente pasar la función interna como una dependencia de las pruebas.
function testing(innerFunction: () => number) { return () => innerFunction(); } export {testing} import { testing } from '../utils' it('should be okay', () => { const mock = () => 33 // AKA System under test const sut = testing(mock) expect(sut()).toBe(33); });Las pruebas pueden ser más simples sin bromas, y también más predecibles...
Mueva la función interna a otro archivo y use jest.mock
export function innerFunction() { return 33 } import { innerFunction } from './innerFunction.ts' function testing() { return innerFunction(); } export { testing } jest.mock('./innerFunction', () => { return () => 33 }); import { testing } from '../utils' it('should be okay', () => { expect(testing()).toBe(33); });