反应测试库 toHaveBeenCalled 0 模拟一个简单的点击道具
react testing library toHaveBeenCalled 0 mocking a simple click prop
我尝试模拟一个名为 actionClicked 的道具,但我的测试失败了,我有一个简单的组件如下
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
})
我不确定为什么 actionClicked
没有被调用。
Expected number of calls: >= 1
Received number of calls: 0
有什么想法吗?
出现此行为是因为 userEvent.click
returns 承诺。
首先你应该把你的测试变成 async
然后 await userEvent.click
:
test("render ButtonAction", async () => {
const actionClicked = jest.fn();
render(<ButtonAction actionClicked={actionClicked} />);
await userEvent.click(screen.getByTestId("some-action"));
expect(actionClicked).toHaveBeenCalledTimes(1);
});
我尝试模拟一个名为 actionClicked 的道具,但我的测试失败了,我有一个简单的组件如下
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
})
我不确定为什么 actionClicked
没有被调用。
Expected number of calls: >= 1
Received number of calls: 0
有什么想法吗?
出现此行为是因为 userEvent.click
returns 承诺。
首先你应该把你的测试变成 async
然后 await userEvent.click
:
test("render ButtonAction", async () => {
const actionClicked = jest.fn();
render(<ButtonAction actionClicked={actionClicked} />);
await userEvent.click(screen.getByTestId("some-action"));
expect(actionClicked).toHaveBeenCalledTimes(1);
});