用方法进行Jest测试

时间:2019-01-19 23:51:22

标签: reactjs react-native jestjs

我正在尝试为我的React.Component类中定义的方法编写一个开玩笑的测试。

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

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

在我的Jest文件中,我正在这样做:

import { Math } from './Math'

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

但这给了我一个错误:

  

TypeError:无法读取未定义的属性“ sum”

我应如何解决此问题?我确实尝试过在线查看它,但找不到解决方法。

2 个答案:

答案 0 :(得分:1)

问题是您将Math.sum(x,y)用作静态函数而不是对象引用。

您可以将功能更改为:

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

对象引用要求您将变量传递给构造函数或通过函数动态分配它们。

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. 

有关静态函数的信息,请参见here

有关何时应使用静态函数的信息,请参见here

此外,有关默认导出的信息,请阅读here

答案 1 :(得分:0)

命名导入时,您正在使用default导出。另外:您正在类本身上使用方法sum(就像它是静态方法一样),而不是类的实例。