问题
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