React测试库ToHaveBeencalled 0嘲笑一个简单的单击道具
我尝试模拟一个名为Action Clicked的道具,但我的测试失败了,我的组件很简单,因为
const ButtonAction: React.FC = ({ actionClicked }) => {
const handleClick = (action) => () => actionClicked(action)
return (
<div
data-testid="some-action"
onClick={handleClick('something')}
>
<Icon />
</div>
)
}
这是我的测试,button.spec.tsx,
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import React from 'react'
import ButtonAction from './ButtonAction'
test('render ButtonAction', () => {
const actionClicked = jest.fn()
render(<ButtonAction actionClicked={actionClicked} />)
userEvent.click(screen.getByTestId('some-action'))
expect(actionClicked).toHaveBeenCalled() //failed here
})
我不确定为什么未调用Action> Action CliceClicked
。
Expected number of calls: >= 1
Received number of calls: 0
有什么想法吗?
I try to mock a prop called actionClicked but my test failed, I have a simple component as below
const ButtonAction: React.FC = ({ actionClicked }) => {
const handleClick = (action) => () => actionClicked(action)
return (
<div
data-testid="some-action"
onClick={handleClick('something')}
>
<Icon />
</div>
)
}
this is my test, button.spec.tsx
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import React from 'react'
import ButtonAction from './ButtonAction'
test('render ButtonAction', () => {
const actionClicked = jest.fn()
render(<ButtonAction actionClicked={actionClicked} />)
userEvent.click(screen.getByTestId('some-action'))
expect(actionClicked).toHaveBeenCalled() //failed here
})
I'm not sure why actionClicked
is not been called.
Expected number of calls: >= 1
Received number of calls: 0
Any thoughts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
此行为之所以发生,是因为
userevent.click
返回承诺。首先,您应该将测试变成
async
,然后等待userevent.click
:This behaviour occurs because
userEvent.click
returns a promise.First you should turn your test to
async
and thenawait userEvent.click
: