1

所以,我正在使用 jest & tesing-library 进行集成测试。所以,我有一个名为“Product”的“主要组件”,它引入了另一个组件,我们称之为“ProductListings”。

在“ProductListings”中,我单击一个在功能组件中调用方法的 div。我如何模拟它,以测试它被称为?

  test('Clicking div calls method', async () => {
     render(<Product />);
     // THIS div is in ProductListings component.. that is contained within Product component
     const divToClickAdd = await screen.findByTestId('myDivWithOnClick')
     user.click(divToClickAdd); // clicking this div fires the method
     // how to do this?
     expect.THE-MOCKED-FUNCTION-TO-HAVE-BEEN-CALLED 
 });

// 这就是 ProductListing 的样子(伪)。它是 IN Products 组件,我正在集成测试。

 const ProductListing = () => {

   // I WANT TO MOCK THIS "fireTheAPI" in my test above.
   const fireTheAPI = () => {
      // do some stuff
   }

   return (
     <div onClick={() => fireTheAPI()} data-testId="myDivWithOnClick">this is a product listing item</div>

   )
}

看我的问题。引入包含“内部组件 ProductListings”的父组件,然后我从中获得一个 div,然后单击.. 我需要在其中模拟该函数“fireTheAPI”

顺便说一句,“产品”看起来像:

const Product = () => {
   return (
      <div>
        <WhateverComponent />
        <div>
            <ProductListings /> // <--- mock a function in here
        </div>
     </div>
   )
}
4

1 回答 1

2

我认为这取决于您的功能在做什么。

在这种情况下,如果您期待 API 调用,我建议使用nock来模拟 API 调用。

它看起来像这样

test('Your Test', () => {
    const scope = nock(YOUR_URL).get(YOUR_ENDPOINT).reply(200);

    const product = render(<Product />);
    const divToClickAdd = await product.findByTestId('myDivWithOnClick');

    act(() => {
        fireEvent.click(divToClickAdd);
    });

    await waitFor(() => {
        expect(scope.isDone()).toBe(true);
    });
});

如果您期待一些 DOM 更改,您也可以继续进行测试。

IMO 集成测试应该关注用户操作的结果,因此我们应该着眼于尝试模拟(或测试)所述功能的特定结果,而不是担心模拟特定功能。

于 2020-07-23T04:51:47.040 回答