Find a component by display name when the component is stateless functionality, with Enzyme

I have the following components:

// Hello.js export default (React) => ({name}) => { return ( <div> Hello {name ? name : 'Stranger'}! </div> ) } // App.js import createHello from './Hello' export default (React) => () => { const Hello = createHello(React) const helloProps = { name: 'Jane' } return ( <Hello { ...helloProps } /> ) } // index.js import React from 'react' import { render } from 'react-dom' import createApp from './App' const App = createApp(React) render( <App />, document.getElementById('app') ) 

And I want to set up a test to see if the App component contains one Hello component. I tried the following using Tape and Enzyme :

 import createApp from './App' import React from 'react' import test from 'tape' import { shallow } from 'enzyme' test('App component test', (assert) => { const App = createApp(React) const wrapper = shallow(<App />) assert.equal(wrapper.find('Hello').length === 1, true) }) 

But the result was that the length property of the find result was 0 when I expected it to be 1 . So how do I find the Hello component?

+8
unit-testing reactjs testing stateless enzyme
source share
1 answer

In this case, you can do a couple of things. An enzyme may correspond to component constructors based on the static properties of the .displayName or .name constructor, or by reference equality. As a result, the following approaches should work:

direct link

you can import the actual components into your tests and find them using direct links to the component:

 // NavBar-test.js import NavBar from './path/to/NavBar'; ... wrapper.find(NavBar).length) 

Named Function Expressions

If you use named function expressions to create your stateless function components, the names should still work.

 // NavBar.js module.exports = function NavBar(props) { ... } 

Static .displayName property

You can add the static .displayName property to the components:

 // NavBar.js const NavBar = (props) => { ... }; NavBar.displayName = 'NavBar'; 
+12
source share

All Articles