pavan sai
pavan sai

Reputation: 41

expect(jest.fn()).toHaveBeenCalledWith(...expected) error in testing react

I am getting error expect(jest.fn()).toHaveBeenCalledWith(...expected) Number of calls: 0 .

Code:

There is a component  on submitting * as form value it will call formik on submit which will 
call api asyncronously
and storing data in searchResult.Then i am checking if entered value is * and length of 
response is greater than 1 then i am calling history.push on outside(i mean not inside any 
function)and it is working fine but when i am writing test cases for this it is showing no 
call generated.
const history = useHistory();
interface LocationRoute {
    pathname: string,
    state: any
}
if (searchResult.data&& formvalue == '*') {
    if (searchResult.data.length > 1) {
        console.log('length greater than 1')
        history.push({
            pathname: '/alldata',
            state: { "name": "John", "EndDate": "16-Jun-2024", "Id": "1252", "StartDate": "17-Jun-2020"}
        } as LocationRoute);
    }
    
}

Test cases:

const mockHistoryPush = jest.fn();

jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useHistory: () => ({
    push: mockHistoryPush,
}),
 }));
 describe()......starts
  
  it('should render card with data when clicked for *', async () => {
    SearchWrapper = mount(<CustomerSearch />);
   ..... checked before clicking submit...
   ......
   await act(async () => {

       SearchWrapper.find('button#submit2').simulate('click');
    });
    await act(async () => {
        SearchWrapper.update();
        
    });
    expect(mockHistoryPush).toHaveBeenCalledWith(locationStateMock2);

  }

and locationstatemock2 is

export const locationStateMock2 = { "pathname": "/alldata", "state": { "name": "John", "EndDate": "16-Jun-2024", "Id": "1252", "StartDate": "17-Jun-2020"}}

and error i am getting is .

expect(jest.fn()).toHaveBeenCalledWith(...expected)

Expected: {"pathname": "/alldata", "state":  { "name": "John", "EndDate": "16-Jun-2024", "Id": "1252", "StartDate": "17-Jun-2020"}}

Number of calls: 0

and i am searching with the console statement i kept in code 'length greater than 1' there i see this error

console.error
  Error: Uncaught [TypeError: Cannot read property 'push' of undefined]
      at reportException (C:\react\copy\front-end\node_modules\jsdom\lib\jsdom\living\helpers\runtime-script-errors.js:62:24)
      at innerInvokeEventListeners (C:\react\copy\front-end\node_modules\jsdom\lib\jsdom\living\events\EventTarget-impl.js:333:9)
      at invokeEventListeners (C:\react\copy\front-end\node_modules\jsdom\lib\jsdom\living\events\EventTarget-impl.js:274:3)

can anyone help me here please.Thanks in advance

Upvotes: 1

Views: 15339

Answers (2)

Anubhaw Kumar
Anubhaw Kumar

Reputation: 11

There might be two things, either you have not mocked your route handler, If you have not mocked the handle mock it and if still get the same then you might not have mocked your navigation you can try the below approach.

Mocking useNavigate hook react router v6 : - 
const mockNavigate = jest.fn();
beforeEach(() => {
           jest.spyOn(router, 'useNavigate').mockImplementation(() =>mockNavigate);
           render(<YourComponent />, { route: '/path' });
});

Or either you can Put this one above your tests:

    const mockNavigate = jest.fn();

    jest.mock('react-router-dom', () => ({
              ...(jest.requireActual('react-router-dom') as any),
              useNavigate: () => mockNavigate
    })
    );
    //Put your tests below this

Upvotes: 1

alextrastero
alextrastero

Reputation: 4280

One thing you could try is to remove some async, only wrap in act the methods that trigger a setState.

await act(() => {
  SearchWrapper.find('button#submit2').simulate('click');
});

SearchWrapper.update(); // this one is not async so no need to wrap AFAIK

Although I can't be sure since the click handler is not shown.

Upvotes: 1

Related Questions