0

Based on https://github.com/facebook/jest/blob/master/examples/manual-mocks/models/user.js examples I created my own manual mock:

const RandomNumber = require.requireActual('../RandomNumber');
RandomNumber.prototype.generate = function() {
  return this.min;
};
export default RandomNumber;

For this module:

export default class {
  constructor(min, max) {
    this.min = min;
    this.max = max;
  }

  generate() {
    return Math.floor(Math.random() * (this.max - this.min + 1) + this.min);
  }
}

However I got this error:

TypeError: Cannot set property 'generate' of undefined

I turned out that I need to add .default on object that is returned from requireActual. And the same applies to code that uses getMockFromModule:

const RandomNumberMock = jest.genMockFromModule('../RandomNumber').default;
RandomNumberMock.prototype.generate.mockReturnValue(10);
export default RandomNumberMock;

I didn't see any mention about this in Jest docs, nor their examples use .default property.

Any idea why in my basic setup this is needed?

dragonfly
  • 17,407
  • 30
  • 110
  • 219

1 Answers1

0

Because this is how require (CommonJS) works, other than using ES6 Modules that already do import default.

Tl;DR; ES6's export default someClass is similar to CommonJS's module.export = { default: someClass }

check this answer out.

Ahmed Abdelrahman
  • 778
  • 3
  • 12
  • 30