React Testing Library Mock function not called

谁说胖子不能爱 提交于 2020-12-13 11:04:25

问题


I am pretty new to testing and attempting to write what should be a simple test for our project...

test('Attempt Login', async () => {
   const submitHandler = jest.fn( ()=> console.log('hello'))

  const { debug, getByText, getByTestId, getByPlaceholderText } = render
    (
    <Router>
        <LoginPage submitHandler={submitHandler} />
    </Router> 
    )

    fireEvent.change(getByPlaceholderText("Enter Username"), {
      target: { value: "admin" }
    });

    fireEvent.change(getByPlaceholderText("Enter Password"), {
      target: { value: "Password" }
    });


    fireEvent.click(getByTestId("login-btn"));

    expect(submitHandler).toHaveBeenCalled()
})

My button inside of login

   <Button data-testid="login-btn" type="submit" variant="contained" color="primary"
   onClick={(event)=>submitHandler(event)}>

the testing error

expect(jest.fn()).toHaveBeenCalled()

    Expected number of calls: >= 1
    Received number of calls:    0

      45 |     fireEvent.click(getByTestId("login-btn"));
      46 |   
    > 47 |     expect(submitHandler).toHaveBeenCalled()
         |                           ^
      48 | })
      49 | 
      50 | 

Thanks in advance for any help. I spent way too long on this already -_-

EDIT: attempting to test for the results of clicking the login button

Heres what I'm going trying:

mock an Axios call to the login route
await waitForElement getByText('home')
expect getbytext('home')

Am I on the right track?

Do I need to import the redirect page component and place it inside the router? for example the component for it to redirect to it?


回答1:


As you already figured out, the problem is you are passing the submitHandler mock into LoginPage but you are not using that prop.

To answer your second question

How do I mock a function not passed in as a prop?

Here is how you can mock functions imported from different files with Jest:

import { submitForm } from './ajax.js'; // the function to mock
jest.mock('./ajax.js'); // jest mocks everything in that file

it('should call submitForm correctly', async () => {
  submitForm.mockResolvedValue({ loggedIn: true });
  render(<LoginPage />);
  
  userEvent.click(screen.getByRole('button', { name: 'Login' }));

  expect(submitForm).toHaveBeenCalledTimes(1);
  expect(await screen.findByText('You have logged in successfully')).toBeInTheDocument();
});

Useful links

  • Mocking modules
  • Understanding Jest mocks
  • mockResolvedValue


来源:https://stackoverflow.com/questions/61534459/react-testing-library-mock-function-not-called

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!