0

I have this React component

import React from 'react';

class template extends React.Component {
  render() {
    return (
      <div>
        <p>count: 0</p>
      </div>
    );
  }
}

export default template;

and trying to run this test on it

import React from 'react'; // eslint-disable-line no-unused-vars
import { shallow } from 'enzyme';

    import template from '../common/template';

    describe('template.js', () => {
      it('Renders template success ', () => {
        const wrapper = shallow(<template />);
        const text = wrapper.find('p').text();
        expect(wrapper.length).toEqual(1);
        expect(text).toEqual('count: 0');
      });
    });

Getting following error.

src/components/__tests__/template.js
  ● template.js › Renders template success

    Method “text” is meant to be run on 1 node. 0 found instead.

       6 |   it('Renders template success ', () => {
       7 |     const wrapper = shallow(<template />);
    >  8 |     const text = wrapper.find('p').text();
         |                                    ^
       9 |     expect(wrapper.length).toEqual(1);
      10 |     expect(text).toEqual('count: 0');
      11 |   });

      at ShallowWrapper.single (node_modules/enzyme/build/ShallowWrapper.js:1958:17)
      at ShallowWrapper.text (node_modules/enzyme/build/ShallowWrapper.js:1097:21)
      at Object.text (src/components/__tests__/template.js:8:36)

wrapper.text() is empty. What I am doing wrong?

Running test using this command

eslint src && react-scripts test --env=jsdom --coverage

App is created using create react app https://github.com/facebook/create-react-app

"@types/jest": "^23.3.12",
"enzyme": "^3.8.0",
"enzyme-adapter-react-16": "^1.7.1",
"react-scripts": "2.1.3",
"react": "^16.7.0",

Update:

seems like shallow is not working as expected or I missing something.. adding following two lines in test

console.log('wrapper:::::', wrapper);
console.log('wrapper.text:::::', wrapper.text());

return these output

console.log('wrapper.text', wrapper.text());
   console.log src/components/__tests__/template.js:8
      wrapper::::: ShallowWrapper {}
    console.log src/components/__tests__/template.js:9
      wrapper.text:::::
Developer
  • 25,073
  • 20
  • 81
  • 128
  • 1
    React expects components to be capitalized. Change `template` to `Template`. See this: https://stackoverflow.com/questions/30373343/reactjs-component-names-must-begin-with-capital-letters – Matt Carlotta May 03 '19 at 01:35
  • So true :) Thanks, Add answer, I will accept it. such a small thing took me while. thanks for help... – Developer May 03 '19 at 01:44
  • @MattCarlotta similar type question if you can have look too plz. https://stackoverflow.com/questions/55962409/reactjs-with-materialui-testing-using-jest-enzyme-shallow-text-return-empty – Developer May 03 '19 at 02:06

0 Answers0