A
A
Arthur2019-09-16 15:43:26
React
Arthur, 2019-09-16 15:43:26

How to test bean method with jest/enzyme?

I'm trying to test the component of the list of tudushek.
I wrote a test in which the component is simply rendered.
What else is usually tested in a component?
I'm trying to test a render method that draws things with passed functions, but I don't understand how to check that functions are passed to the rendered component?
Here is the code of the component under test

import React from 'react';
import Todo from '../Todo'
import {Pane, Heading} from 'evergreen-ui';
import PropTypes from 'prop-types';

const TodoList = ({todos, TODO_UPD}) => {
  const renderBlocks = () => {
    return todos.map(block => {
      return <Todo
        key={block.id}
        complete={block.complete ? 'completed' : ''}
        text={block.text}
        onBlockClick={() => TODO_UPD(block.id)}
      />
    });
  };

  return (
    <Pane>
      {renderBlocks()}
    </Pane>
  );
};

TodoList.propTypes = {
  data: PropTypes.arrayOf(PropTypes.shape(
    {
      id: PropTypes.number.isRequired,
      text: PropTypes.string.isRequired,
      complete: PropTypes.bool.isRequired,
    }),
  ),
};

export default TodoList;

and here is the test code in which I want to check the passed functions exist and work
describe('TodoList test', () => {
  const props = {
    todos: [{id: 1, complete: false, text: '1'},{id: 2, complete: false, text: '2'},{id: 3, complete: true, text: '3'}],
    TODO_UPD: jest.fn(),
  };

  it('should render todos with OnBlockClick func', () => {
    const wrapper = shallow(<TodoList {...props} />);
    const todo = wrapper.find(Todo).at(0);
    todo.simulate('click');
    expect(props.TODO_UPD).toBeCalled();
  });
});

This test fails with an error.

expect(jest.fn()).toBeCalled()
Expected mock function to have been called, but it was not called.

How to test correctly? what else is usually tested in such components?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Arthur, 2019-09-16
@cloudz

testing the execution of functions on nested components should be done through the mount of the component, instead of shallow

it('should render todos with OnBlockClick func', () => {
    const wrapper = mount(<TodoList {...props} />);
    const todo = wrapper.find(Todo).at(0);
    todo.simulate('click');
    expect(props.TODO_UPD).toBeCalled();
  });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question