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

176
Visualizações
When unit testing mjs files, is there a way to mutate an imported function without using jest.mock?

Using module mocks in Jest has been done since the dawn of time, however as we move into the world of mjs it's impossible to intercept calls to require at runtime to enable this pattern.

jest.mock('./filename')

While I generally try my best to parameterize my dependencies, there are some cases where it's not possible (such as third party dependencies) or it's inconvenient and I need to explicitly mock out a single or multiple properties in a module.

I have tried various ways to reassign a property:

// foo.mjs
export function foo() {
  console.log('foo')
}

Simple reassignment - fails

import { foo } from './foo.mjs'
import * as fooModule from './foo.mjs'

fooModule.foo = function() { 
  console.log('bar')
}

console.log(foo())

Object.defineProperty - fails

import { foo } from './foo.mjs'
import * as fooModule from './foo.mjs'

Object.defineProperty(fooModule, 'foo', { value: function() { 
  console.log('bar')
}})

console.log(foo())

Object.assign - fails

import { foo } from './foo.mjs'
import * as fooModule from './foo.mjs'

Object.assign(fooModule, {
  foo: function() { 
    console.log('bar')
  }
})

console.log(foo())

All of these attempts fail with

TypeError: Cannot assign to read only property 'foo' of object '[object Module]'

In new Node with modules, is there an expected way to monkey patch modules or parts of a module such that all subsequent imports of that module receive that patch?

about 4 years ago · Juan Pablo Isaza
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