what's wrong with this jest test setup?

Viewed 23

I have a React app and I'm trying to create a basic Jest unit test. I've created a basic Calculator class like this within a Calculator.js file:

class Calculator{
    add(num1, num2){
        return num1 + num2;
    }
}
export default Calculator;

At the same level, I've created a new Jest unit test named Calculator.test.js like this:

import './Calculator';

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

However, when the Jest test harness runs, the following error gets output:

ReferenceError: Calculator is not defined

  3 |
  4 | test('adds 1 + 2 to equal 3', () => {
> 5 |   expect(new Calculator().add(1, 2)).toBe(3);
    |              ^
  6 | });
  7 |

  at Object.<anonymous> (src/services/Calculator.test.js:5:14)

Any idea what I'm doing wrong with this particular implementation?

1 Answers

Try this in your Calculator.test.js:

import Calculator from './Calculator';

Empty import (as in import './Calculator';) only loads the module, but doesn’t actually import anything.

Related