单击按钮后在 Jest 中测试函数调用(模拟提取调用)

Testing function calls in Jest after button click (mocking fetch calls)

我正在 运行为 React SPA 使用 Jest 测试套件。我正在尝试为登录页面编写测试。如果登录尝试的结果是 404,我应该调用一些函数,但我不明白为什么没有调用它们。

我正在尝试模拟对用户进行身份验证的提取调用,并确保之后调用正确的函数。下面的代码试图做的是:

import { render, fireEvent } from "@testing-library/react";
import React from "react";
import SignIn from "./signIn";
import 'jest-dom/extend-expect';
import 'isomorphic-fetch';

const mockResponse = (status: number, response: BodyInit) => {
    const fetchResponse: Response = new Response(response, {status:status});
    return fetchResponse;
}

describe("<SignIn>", () => {
it("sets basic creds, auth header, usingIMS, and authenticated when it gets a 404", async () => {
    const setBasicCreds = jest.fn();
    const setAuthHeader = jest.fn();
    const setUsingIms = jest.fn();
    const setAuthenticated = jest.fn();
    const baseUrl = 'https://testUrl';

    const fakePromise = Promise.resolve(mockResponse(404, JSON.stringify({message: "test"})));
    window.fetch = jest.fn().mockImplementationOnce(() => {
        return fakePromise;
    });

    const { getByTestId } = render(<SignIn baseUrl={baseUrl} setBasicCreds={setBasicCreds} setAuthenticated={setAuthenticated}
    setAuthHeader={setAuthHeader} setUsingIms={setUsingIms} connectionName={signInProps.connectionName}></SignIn>);

    const username: HTMLElement = getByTestId("signInUsername");
    fireEvent.change(username, {
        target: { value: 'username' },
      });

    const password: HTMLElement = getByTestId("signInPassword");
    fireEvent.change(password, {
        target: { value: 'password' },
      });

    const submitButton: HTMLElement = getByTestId("signInSubmitButton");
    fireEvent.click(submitButton);

    await Promise.all([fakePromise]);
    expect(setBasicCreds).toHaveBeenCalled();
    expect(setAuthHeader).toHaveBeenCalled();
    expect(setUsingIms).toHaveBeenCalledWith(false);
    expect(setAuthenticated).toHaveBeenCalledWith('Authenticated');
    });
});

当测试套件为 运行 时,它在第一个 expect 上失败,表示从未调用 setBasicCreds。我错过了什么?

很久以后跟进我的问题,答案是使用集成测试。我尝试做的事情对于使用像 Cypress 这样的框架进行的集成测试比 Jest 单元测试更有意义。