【问题标题】:Multiple fetch calls using fetchMock & `userEvent.click` within a `test.each` using React Testing Library使用 React 测试库在 `test.each` 中使用 fetchMock 和 `userEvent.click` 进行多次 fetch 调用
【发布时间】:2020-06-01 13:06:44
【问题描述】:

鉴于对我们正在向其发出请求的端点的回调响应,我希望测试一些结果。

给定以下代码:

describe('when I click the "continue to shop" button', () => {
test.only.each`
    applicationStatus                     | routeName                   | routeURL
    ${'CASH_ACCEPT'}                      | ${'Checkout Shipping'}      | ${'/checkout/shipping.page'}
    ${'DECLINED'}                         | ${'Account Rejected'}       | ${'/account/application/accountRejected.page'}
    ${'EXISTING_ACCOUNT_PROFILE_MATCHED'} | ${'Existing Account Found'} | ${'/account/accountFound.page?email=c***********4@example.com'}
    ${'a non-recognised'}                 | ${'Server Error'}           | ${'/serverError.page'}
`(
    'then the $applicationStatus response should take me to the $routeName page',
    async ({ applicationStatus, routeURL }) => {
        fetchMock.post(`/api/account-application/applications`, {
            data: {
                id: '123',
                type: 'account-application',
                attributes: {
                    applicationStatus: `${applicationStatus}`,
                    email: 't*********@example.com',
                },
            },
        });

        const component = render(<Benefits experiments={experiments} />);

        await act(async () => {
            await userEvent.click(component.getByText(/Continue to shop/i));
        });

        expect(component.getByTestId('loading-overlay'));

        // eslint-disable-next-line security/detect-non-literal-fs-filename
        expect(global.open).toBeCalledWith(`${routeURL}`, '_self');
    },
);

我希望每个测试迭代只触发一次但是,似乎每个测试都失败了。似乎userEvent.click 不止一次发生并且正在保存上一次点击:

Expected: "/account/accountFound.page?email=c_**\***_4@example.com", "\_self"
Received
1: "/checkout/shipping.page", "\_self"
2: "/account/application/accountRejected.page", "\_self"
3: "/account/accountFound.page?email=t**\***@example.com", "\_self"

Number of calls: 3

我的理解是,每次测试后,cleanup 都会运行,并且应该在下一次之前重置一切。谁能看到我在这里做错了什么?谢谢!

【问题讨论】:

    标签: javascript jestjs react-testing-library


    【解决方案1】:

    失败的是 expect(global.open) 断言,而不是 userEvent.click

    默认情况下,Jest 不会重置 spy 调用,并且在提供的代码中不会执行手动清理。

    使用resetAllMocksrestoreAllMocks

    afterEach(() => {
      jest.restoreAllMocks();
    });
    

    后者需要在每次测试之前设置global.open spy,而不是只设置一次。

    或者更好的是,启用resetMocksrestoreMocks 配置选项,因为在编写良好的测试中几乎不希望出现交叉污染。

    【讨论】:

      猜你喜欢
      • 2021-01-08
      • 1970-01-01
      • 2019-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-29
      • 1970-01-01
      • 2022-01-19
      相关资源
      最近更新 更多