0

I have a simple JavaScript file like this:

// sum.js
function sum(a, b) {
  return a + b;
}
export default { sum };

and I want to test that file with jest in same folder like this:

// sum.test.js
const { sum } = require('./sum')

test('adds 1 + 2 to equal 3', () => {
  expect(sum(1, 2)).toBe(3);
});

test fails that way however everything works perfect if I export as module.exports = sum;instead export default { sum }; but I'm not allowed to change original js file so I could only change test file. How can I complete my test succesfully with that situation?

Solutions I've tried (but failed are below)

  • const { sum } = require('./sum').default
  • const { sum } = require('./sum').default()
  • import { sum } from './sum'
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
Kaan G
  • 219
  • 4
  • 13
  • I tried installing `@babel/plugin-transform-modules-commonjs` and using `const { sum } = require('./sum').default` worked for me for some reason. Perhaps your transform configuration is messing something up somewhere, you can log the result of `require('./sum')` to see what happens, it might give you an idea – CertainPerformance Jan 05 '20 at 00:21
  • I've installed plugin and used `.default` but it still throwed me same error @CertainPerformance https://paste.ubuntu.com/p/nyHtdF6GcT/ – Kaan G Jan 05 '20 at 01:03
  • Check out https://github.com/CertainPerformance/jestrequire-problems if you're curious, I just made it to demonstrate. It's extremely bare-bones, `npm install` then `npm test` runs without problems. Make sure to have `"@babel/plugin-transform-modules-commonjs"` inside `.babelrc` as a test plugin – CertainPerformance Jan 05 '20 at 01:23

1 Answers1

1

It's pretty weird to have a default export be an object with a single property, because it means that accessing the value there will take at least two lines. First use import without brackets to get to the object, then extract the property from it:

import sumObj from './sum';
const { sum } = sumObj;

It looks a bit ugly. Ideally you'd want to change the sum.js file to either have named exports - eg, have sum be a named export, so it can then be imported easily:

export function sum(a, b) {
import { sum } from './sum';

(but, if you can't change the original file, that's unfortunate)

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • probably offtop, but do you have any ideas why `const { sum } = require('./sum').default` may not work here? to me looks equal to "explicit default import + destructuring". am checking https://github.com/webpack/webpack/issues/4742 if that answers this – skyboyer Jan 05 '20 at 00:04