Enzyme: how to access functions inside SFC (stateless functional component) in react for testing them

Created on 30 Oct 2019  路  2Comments  路  Source: enzymejs/enzyme

import React from "react";

import { TestState } from "../store/dataFetching/types";

import Node from "./node";

import "../styles/node.css";

type Props = {
  fetchedData: TestState;
  fetchData: Function;
};

/**
 * @name NodeList
 * @description this component is responsible for rendering the list of nodes
 * @param props
 */
const NodeList: React.SFC<Props> = props => {
  /**
   * @name renderNodeList
   * @description this function is used to rendering list of nodes if its length wasn't 0
   */
  function renderNodeList() {
    return props.fetchedData.list.length !== 0
      ? props.fetchedData.list.map((node, index) => (
          <Node key={index} nodeSpec={node} />
        ))
      : null;
  }
  return (
    <div className="parent">
      {renderNodeList()}
      <button onClick={() => props.fetchData()}>update store</button>
    </div>
  );
};

export default NodeList;

this was my stateless components , i wanted to test specifically renderNodeList() , how can i get access to it in my tests ?!

question

Most helpful comment

You can't, directly. The nature of the JavaScript language means that you can never access things hidden inside a closure.

In this case, you can test it by shallow rendering NodeList, and asserting on the non-button children of the div it renders.

All 2 comments

i'm using :
"@types/react": "16.9.9"
"@types/jest": "24.0.19"

You can't, directly. The nature of the JavaScript language means that you can never access things hidden inside a closure.

In this case, you can test it by shallow rendering NodeList, and asserting on the non-button children of the div it renders.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

aweary picture aweary  路  3Comments

benadamstyles picture benadamstyles  路  3Comments

timhonders picture timhonders  路  3Comments

blainekasten picture blainekasten  路  3Comments

ahuth picture ahuth  路  3Comments