Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 使用传递的值测试组件方法的返回值_Reactjs_Testing - Fatal编程技术网

Reactjs 使用传递的值测试组件方法的返回值

Reactjs 使用传递的值测试组件方法的返回值,reactjs,testing,Reactjs,Testing,嗨,我正在尝试对一个组件方法进行测试,该组件方法以数字形式传递并返回字符串。这是我第一次在react中进行写作测试,在我的情况下,我找不到任何可以做什么的例子 我的代码 import moment from "moment"; import React from 'react'; class ReactPage extends React.Component { //some other functions //turn number into money (returns strin

嗨,我正在尝试对一个组件方法进行测试,该组件方法以数字形式传递并返回字符串。这是我第一次在react中进行写作测试,在我的情况下,我找不到任何可以做什么的例子

我的代码

import moment from "moment";
import React from 'react';
class ReactPage extends React.Component {
  //some other functions

  //turn number into money (returns string)
  commafyMoney = (money) => {
    return "$"+ money.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
  }

  //return fancy react webpage
  render(){
    return(
      //stuff
    );
  }
}
export default ReactPage; 
这是我测试返回值的尝试

import {shallow, mount, render, configure} from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import ReactDOM from 'react-dom';
import ReactPage from './App';

it('commafyMoney(number)', () => {
  const wrapper = shallow(<ReactPage />);
  expect(wrapper.instance().commafyMoney(1234.56)).toEqual("$1,234.56");
});
import{shall,mount,render,configure}来自'enzyme';
从'enzyme-Adapter-react-16'导入适配器;
从“react dom”导入react dom;
从“/App”导入页面;
它('commafyMoney(数字)',()=>{
常量包装器=浅();
expect(wrapper.instance().commafyMoney(1234.56)).toEqual($1234.56);
});
有人知道如何修复此测试以使其正常工作吗?

选项1:wrapper.instance() 你缺少了一些设置酶所需的华夫饼干

import React from 'react'; // React must be in scope any time you write jsx.

configure({ adapter: new Adapter() }); // Let enzyme use the adapter.
在导入后添加这些行,测试应该通过。(假设jest配置正确。)

选项2:不渲染组件。 由于您正在测试的方法不会直接影响组件的渲染,因此您可以只获取组件的实例而不进行渲染

import ReactPage from './App';

it('commafyMoney(number)', () => {
  const page = new ReactPage;
  expect(page.commafyMoney(1234.56)).toEqual("$1,234.56");
});
这就提出了一个问题,为什么该方法是在类中定义的,而不是从其他地方导入的实用函数。您最好将该方法移动到另一个更容易测试的模块