【问题标题】:React Jest test with method用方法反应 Jest 测试
【发布时间】:2019-06-13 19:17:49
【问题描述】:

我正在尝试为我的 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: 无法读取未定义的属性“总和”

我应该如何解决这个问题?我确实尝试在网上查看但找不到解决方案。

【问题讨论】:

标签: reactjs react-native jestjs


【解决方案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

【讨论】:

  • 好的,但将来我想在静态方法中添加这个实例,你不能在静态方法中访问它,因此试图找到更好的解决方案。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-12
    • 1970-01-01
    • 1970-01-01
    • 2020-08-27
    • 2018-08-30
    • 2020-08-22
    • 1970-01-01
    • 2015-07-10
    相关资源
    最近更新 更多