value must be a mock or spy function when using jest.fn

randal

Getting this error

Matcher error: received value must be a mock or spy function

Received has type:  object
Received has value: {}

However, i think i shouldn't be getting this error because im using jest.fn. So im mocking the function.

describe('Should simulate button click', ()=> {
        it('should simulate button click', () => {
            // add the name of the prop, which in this case ites called onItemAdded prop,
            // then use jest.fn()
            const wrapper = shallow(<TodoAddItem onItemAdded={() => jest.fn()}/>)
            // console.log('props',wrapper.find('button').props());
            wrapper.find('button').simulate('click');

            expect(wrapper).toHaveBeenCalled(); // error happens when this executes
        })
    })

todo-add-item.js

import React, { Component } from 'react';

import './todo-add-item.css';

export default class TodoAddItem extends Component {

    render() {
        return (
            <div className="todo-add-item">

                <button 
                    className="test-button btn btn-outline-secondary float-left"
                    onClick={() => this.props.onItemAdded('Hello world')}>
                    Add Item
                </button>
            </div>
        );
    }
}

app.js (using the component in this file)

import React, { Component } from 'react';

import AppHeader from '../app-header';
import SearchPanel from '../search-panel';
import TodoList from '../todo-list';
import ItemStatusFilter from '../item-status-filter';
import TodoAddItem from '../todo-add-item';

import './app.css';

export default class App extends Component {

    constructor() {
        super();

        this.createTodoItem = (label) => {
            return {
                label,
                important: false,
                done: false,
                id: this.maxId++
            }
        };

        this.maxId = 100;

        this.state = {
            todoData: [
                this.createTodoItem('Drink Coffee'),
                this.createTodoItem('Make Awesome App'),
                this.createTodoItem('Have a lunch')
            ]
        };

        this.deleteItem = (id) => {
            this.setState(({ todoData }) => {
                const idx = todoData.findIndex((el) => el.id === id);
                const newArray = [
                    ...todoData.slice(0, idx),
                    ...todoData.slice(idx + 1)
                ];

                return {
                    todoData: newArray
                };
            });
        };

        this.addItem = (text) => {
            const newItem = this.createTodoItem(text);

            this.setState(({ todoData }) => {
                const newArray = [
                    ...todoData,
                    newItem
                ];

                return {
                    todoData: newArray
                };
            });
        };

        this.onToggleImportant = (id) => {
            console.log('toggle important', id);
        };

        this.onToggleDone = (id) => {
            console.log('toggle done', id);
        };
    };

    render() {
        return (
            <div className="todo-app">
                <AppHeader toDo={ 1 } done={ 3 } />
                <div className="top-panel d-flex">
                    <SearchPanel />
                    <ItemStatusFilter />
                </div>
                <TodoList
                    todos={ this.state.todoData }
                    onDeleted={ this.deleteItem }
                    onToggleImportant={ this.onToggleImportant }
                    onToggleDone={ this.onToggleDone } />
                <TodoAddItem onItemAdded={ this.addItem } />
            </div>
        );
    };
};
Diogo Capela

I'm not 100% sure, but I believe you should do something like this:

describe('should simulate button click', () => {
   it('should simulate button click', () => {
      const mockedFunction = jest.fn();

      const wrapper = shallow(<TodoAddItem onItemAdded={ mockedFunction } />);

      wrapper.find('button').simulate('click');

      expect(mockedFunction).toHaveBeenCalled();
   });
});

You are testing if the onItemAdded function gets called when you click the <TodoAddItem /> component. So you have to mock it first using jest.fn and then check if the mocked function got called after you simulated the click.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

jest.fn() value must be a mock function or spy

How to test condition function with Jest - Error: Matcher error: received value must be a mock or spy function

Spy on Jest mock

Jest unit test. Mock function return, spy on function call

Jest: having trouble keeping a reference of a mock function with `jest.fn()`

Jest doesn`t mock(set spy) on needed function

How to reset a spy or mock in jest

How to spy/mock minimatch with jest

mock function is not being called despite passing jest.fn as a prop

How to test jest.fn().mock.calls in asynchronous function

How to mock a function that returns a function using jest

Jest mock the return value of an imported function

How to test a return value of a mock function in jest

How to spy on a class property arrow function using Jest

cannot mock function in useEffect when toMatchSnapshot in Jest

How to mock/spy useState hook in jest?

Simple Mock Function of Passport using Jest

Mock request module function using jest in typescript

Jest jest.mock function with different return value

Jest Spy says function is not called

Spy on default exported function with Jest

How to spy on a function that is imported in jest

mock one function using jest.mock() and not another in the same file

How to mock a primitive const value using jest and restore the mock?

How to mock interceptors when using jest.mock('axios')?

Jest mock function arguments don't match when using immutable data structures

Jest: How to mock one specific function when using module.exports

Jest how to check spy function being called within a spy function?

Cannot mock a function in Jest