obaram
obaram

Reputation: 461

How to unit test function in React App with JEST

Hi I am quite new in testing in JEST that why I want to ask you about some support.
I`m trying to test function from App.js component in my App.test.js but I recive a error:

TypeError: _App.default.avg is not a function.

Here is my App.js component

class App extends React.Component {

 state={ }

 avg = (elements) => {   
 let sum=0;    
 for(let i=0; i<elements.length; i++){
     sum += elements[i].main.temp;
 }
 return (sum/elements.length).toFixed(2);
 }

  render() {
    return(
      <BrowserRouter>
          <AppContext.Provider value={contextElements}>
              <div className="App container">             
                <Route path="/" component={SettingsBar}/>               
                <Route path="/settings" component={SettingsView}/>               
                <Route exact path="/" component={RootView}/>
                <Route  path="/itemview" component={ItemView}/>
              </div>
          </AppContext.Provider>     
      </BrowserRouter>

    )  
  }
}
export default App;


And App.test.js

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

describe('avg', () => {

     it('should return 3 for given array [1,2,3,4,5]', () => {
         expect(App.avg([1,2,3,4,5])).toBe(3);
     });

});

What I`m doing wrong?

Upvotes: 1

Views: 1999

Answers (1)

Parker Lindley
Parker Lindley

Reputation: 104

You may want to try making an instance of your App.js class.

So after import you could try something like

const myApp = new App();

Then, in your expect, call myApp.avg(arguments).

Upvotes: 1

Related Questions