0

I am trying to write a jest test for a method defined in my React.Component class.

class Math extends React.Component {
constructor(props) {
   super(props);
}

sum(a, b){
  return a+b; 
}
export default Math;

and in my Jest file I am doing this:

import { Math } from './Math'

 describe('Math', () => {
 it('should add correctly', () => {
  const result = Math.sum(10, 10);
  expect(result).toEqual(20);
 } 

But it gives me an error saying:

TypeError: Cannot read property 'sum' of undefined

How should I resolve this issue ? I did try to look it online but couldnt find the solution.

skyboyer
  • 22,209
  • 7
  • 57
  • 64
lifemoveson
  • 1,661
  • 8
  • 28
  • 55

2 Answers2

1

The issue is you're using Math.sum(x,y) as a static function instead of an Object reference.

You can change your function to:

static sum(a, b){
  return a + b; 
}

Object references call for you to pass variables to the constructor or dynamically assign them through a function.

let x, y;
class Math {
 //The constructor has optional parameters which default to 0. 
 constructor(first=0, second=0){
  this.x = first;
  this.y = second;
}

//Makes a sum with the variables passed through the constructor.
sum(){
 return x+y;
}

//sets the x value
changeX(num){ x = num; }

//returns the x value
getX(){ return x; }

//This function saves it to the object beforehand so you may retrieve it later. 
sumSaved(first, second){
  this.x = first;
  this.y = second;
return x + y;
} 

//Assigned through the constructor.
let foo = new Math(first:1,second:2);
foo.sum(); //returns 3 because 1+2=3
foo.changeX(2);
foo.sum(); //returns 4 because 2+2=4

//Assigned through a function.
let bar = new Math();
bar.sumSaved(4,6); //returns 10 and overwrites variables.
bar.getX(); //returns 4, because you saved it earlier. 

See here for information on static functions.

See here on when you should use static functions.

Also, for information about default exports, read here.

sheepiiHD
  • 421
  • 2
  • 16
  • ok but in future I am thinking to add this instance as well inside the static method and you cannot access this inside a static method hence was trying to find a better solution. – lifemoveson Jan 20 '19 at 01:20
0

You are using a default export while your import is named. Also: you are using the method sum on the class itself (like it was a static method) instead of an instance of the class.

inyono
  • 424
  • 2
  • 6