未调用 React 测试库模拟函数
我对测试很陌生,并试图为我们的项目编写一个简单的测试......
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()
})
登录里面的我的按钮
<Button data-testid="login-btn" type="submit" variant="contained" color="primary"
onClick={(event)=>submitHandler(event)}>
测试错误
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 -_-
尝试测试点击登录按钮的结果
attempting to test for the results of clicking the login button
这是我要尝试的:
mock an Axios call to the login route
await waitForElement getByText('home')
expect getbytext('home')
我在正确的轨道上吗?
我是否需要导入重定向页面组件并将其放置在路由器中?例如它重定向到它的组件?
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?
正如您已经发现的,问题是您将 submitHandler
模拟传递到 LoginPage
没有使用那个道具.
As you already figured out, the problem is you are passing the submitHandler
mock into LoginPage
but you are not using that prop.
回答你的第二个问题
如何模拟未作为 prop 传入的函数?
How do I mock a function not passed in as a prop?
以下是如何使用 Jest
模拟从不同文件导入的函数:
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();
});