samedi 4 janvier 2020

how to test js files which exported with export default?

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'

Aucun commentaire:

Enregistrer un commentaire