namrata salaskar
namrata salaskar

Reputation: 31

In React functional Component , test internal functional using jest and enzyme

I am using functional Component in React , I need to write unit test case for a method in functional component.

import React from 'react';
function print(){
  console.log('hello');
}
    
function Welcome(props){
  return <h1>{props.name}</h1>;
}
    
export default Welcome; 

In jest and enzyme :

test (method print , ()=> {
  const container =  shallow(<Welcome />).instance().print()
}

instance : TypeError Cannot read property of null

I have read functional component don't have an instance in React 16+ . Would someone help in suggesting a way to write unit test cases for methods in functional component.

Upvotes: 0

Views: 3482

Answers (2)

k-wasilewski
k-wasilewski

Reputation: 4613

I'd just want to remind you that you don't / can't test a functional component's functions "by themselves", you only test their implementation.

So, as @EstusFlask pointed out, you can't make an instance of an FC an then call it's function in a test case; but you can just use this function in your FC (and you should, that's the point of creating a function) and then in your test case - test the output / results of this function's execution.

Upvotes: 1

Estus Flask
Estus Flask

Reputation: 222309

print function is defined in module scope. As with any other scoped values, it cannot be accessed outside the scope.

In order to be accessible, it should be exported:

export function print(){  console.log('hello');  }

It cannot be mocked when being declared in the same module it's used. print is not a method and functional components don't have instances that could have methods. It cannot be accessed as instance().print, unless it was exposed with useImperativeHandle.

Upvotes: 0

Related Questions