如何在create react app中测试一个简单的功能?

时间:2018-09-11 02:37:18

标签: reactjs testing jestjs

我是测试新手。我正在尝试使用jest测试我的App.js文件夹中的2个功能。我正在尝试将测试添加到App.test.js文件夹。当我运行npm test时,它会找到默认的“渲染而不崩溃”和我的测试。默认测试当然可以通过,但是我的测试失败了,开玩笑说 ReferenceError: parentFinder is not defined。我已经导入了App.js文件夹,所以我不确定为什么它是未定义的。它不应该在App.js文件中找到要测试的功能吗?

App.js:

import React, { Component } from 'react';
import './App.css';
import Input from './components/PageWrapper/Input';
import Output from './components/PageWrapper/Output';
import PageHeader from './components/PageWrapper/PageHeader';
import ResetInputButton from './components/PageWrapper/ValidateButton';
import ValidateButton from './components/PageWrapper/ValidateButton';

class App extends Component {
  constructor(props){
    super(props)
    this.state = {
      inputData: "",
      outputData:""
    }
  }

  change = e => {
   this.setState({inputData: e.target.value})
   // console.log("e.target.value")
  }

  parentFinder = (data,obj) => {
    let z = 0;
    while (data[z] != null){
      var found = data[z].find((element) => {
        if (element.id === obj.parent_id){
          return element
        }
      });
      if(found != null){
        found.children.push(obj)
      }
      z += 1;
    }
  }

  validationHandler = e => {
    if(this.state.inputData !== "") {
      var data = JSON.parse(this.state.inputData)
      var i = 0;
    while (data[i] != null){
    for (var j = 0; j < data[i].length; j++){
      if (data[i][j].parent_id != null){
      this.parentFinder(data,data[i][j])
      }
     }
    i += 1;
   }
   this.setState({outputData:JSON.stringify(data[0],null,5)})
  } else {
    alert("Please enter some data!")
  }
 }

 resetHandler = (e) => {
   this.setState({inputData:""})
   this.setState({outputData:""})
 } 

  render() { 
    return (  
      <div className="wrapper">
        <PageHeader />
        <Input name="inputData" value={this.state.inputData} onChange={this.change} placeholder={'Paste JSON Here'}/>
        <div className="buttonWrapper">
          <ValidateButton title={'Validate'} onClick={this.validationHandler}/> 
          <ResetInputButton title={'Reset Input'} onClick={this.resetHandler}/>
        </div> 
          <Output type="text" value={this.state.outputData}> </Output>
      </div>
    );
  }
}

export default App;

这是我的App.test.js:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

it('renders without crashing', () => {
  const div = document.createElement('div');
  ReactDOM.render(<App />, div);
  ReactDOM.unmountComponentAtNode(div);
});



test('parentFinder returns null', () => {
  expect(parentFinder(0,obj)).toBeNull();
});

2 个答案:

答案 0 :(得分:0)

parentFinderobj未在测试文件中的任何位置声明,并且未全局定义,因此您将收到“未定义”错误。

根据您的示例,我假设您的意思是:

parentFinder = (data,obj) => { // <---- this?
    let z = 0;
    ...

如果是这种情况,则obj指的是要传递到App.parentFinder方法中的元素(即正在创建的新div)。由于parentFinderApp组件上的一种方法,因此您需要获取App的实例。我建议使用Test Renderer

您可以通过执行以下操作来完成此操作:

import React from 'react';
import App from './App';
import TestRenderer from 'react-test-renderer';

test('parentFinder returns null', () => {
  // have the TestRenderer create your App
  const app = TestRenderer.create(<App />);

  // to get the mounted app component instance
  const appInstance = app.getInstance();

  // not sure what you mean by 0,obj in your example
  // but you would pass in your "data"/"obj" values here
  const result = appInstance.parentFinder();
});

希望这对您有所帮助。

答案 1 :(得分:0)

您还可以使用酶(https://airbnb.io/enzyme)获取该组件的实例。代码将如下所示:

import React from 'react';
import App from './App';
import { shallow } from 'enzyme';

test('parentFinder returns null', () => {
  const wrapper = shallow(<App />);
  expect(wrapper.instance().parentFinder(0,obj)).toBeNull();
});