79458221

Date: 2025-02-21 17:44:55
Score: 0.5
Natty:
Report link

I know it's been a while, but as of 2025, after days of searching, I discovered that unfortunately, mock doesn't work with Javascript ES6 (ECMAScript). Read here

// sample-module.js
export const value = 'value'
export const aFunction = () => 'a Function is called'
export default () => 'I am a default export'

export function add(a, b) {
  return a + b
}

Instead we must use jest.unstable_mockModule

// sample-module.test.js
import { expect, it, jest } from '@jest/globals'
import defaultExport2, { aFunction as oldFunction } from './sample-module.js'

console.log('oldFunction:', oldFunction()) // oldFunction: a Function is called
console.log('defaultExport2:', defaultExport2()) // defaultExport2: I am a default export


jest.unstable_mockModule('./sample-module.js', () => ({
  default: jest.fn(() => 'mocked that doesn\'t work'), // here doesn't work
  value: 'mocked value',
  aFunction: jest.fn(),
  add: jest.fn(),
}))

const { default: defaultExport, value, aFunction, add } = await import('./sample-module.js')
// const defaultExport = await import('./sample-module.js')

it('should do a partial mock', () => {
  expect(value).toBe('mocked value')

  const defaultExportResult = defaultExport.mockReturnValue('mocked default export')()
  expect(defaultExportResult).toBe('mocked default export')
  expect(defaultExport).toHaveBeenCalledTimes(1)

  aFunction.mockReturnValue('aFunction mocked')
  expect(aFunction()).toBe('aFunction mocked')

  add.mockImplementation((a, b) => a * b)
  expect(add(6, 12)).toBe(72)
})

it('add is an empty function', () => {
  expect(add()).not.toBeDefined()
})
Reasons:
  • Blacklisted phrase (1): I know it's been
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: Nima