在div onclick上模拟的方法上单击时,Jest / javascript测试库模拟未触发

时间:2020-07-26 03:15:13

标签: jestjs react-testing-library

设置: 我正在做一个集成测试。有父组件,它引入了两个子组件。子组件中的一个具有onClick,该onClick调用该子组件文件中的方法。我导出该方法,对其进行模拟。

问题: 在测试中,我正在通过onclick找到“ div”,触发一个事件。但是toHaveBeenCalledOnce并未显示已被调用。触发事件时会调用实际的方法,但“ spyon”实际上并未监视它。

代码:

// import the the file to be mocked, This is a child component
 import * as ProductList from '../ProductList';

// Mock the exported method that I have OUTSIDE the functional component.
  test('Div click', async () => {
    render(<Products />);
    const divToClickAdd = await screen.findByTestId('item17');
    // this doesn't appear to spyOn it.
    const jsonSpy = jest.spyOn(ProductList, 'myMethodToFireAnAction');

    act(() => user.click(divClick));
    // this fails as it is called 0 times
    // I also added a waitFor thinking it was a timing thing, still didn't work
    await expect(jsonSpy).toHaveBeenCalledTimes(1);
 }

儿童组件文件:伪代码-ProductListing

 export const myMethodToFireAnAction = (id) => {
    // do some stuff. If I comment in here, it does fire.
 };
 
// This is the child component. It renders a list of divs that have an onclick calls that
// method above and passes the id.
const ProductListing = (products) => {

1 个答案:

答案 0 :(得分:0)

该内部方法被视为实现细节,我们希望避免对其进行测试。相反,您可以通过触发该方法来测试该用户对哪些功能进行了更改。如果它引入了新的DOM节点,更改了元素的样式等。

如果您确实需要测试该方法,则可以将其作为道具传递给组件,然后在测试中执行以下操作:

const onClickMock = jest.fn()

render(<Component onClick={onClickMock} />)
    
// fire click event 

expect(onClickMock).toHaveBeenCalledTimes(1)